diff --git a/Cargo.lock b/Cargo.lock index 41e0fd603..e840b212b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4862,6 +4862,7 @@ dependencies = [ "parking_lot 0.12.5", "portable-pty", "quick-xml 0.42.0", + "regex", "serde", "serde_json", "specta", diff --git a/Cargo.toml b/Cargo.toml index 96ad4883e..7edc66d89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -101,6 +101,7 @@ tar = "0.4" grep-searcher = "0.1" grep-regex = "0.1" regex-syntax = "0.8" +regex = "1" grep-matcher = "0.1" nucleo-matcher = "0.3" redb = "4" diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index 3d359bb17..b3dcba2f2 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -421,13 +421,14 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec { } /// CLion's Build Project for a CMake project: configures the build directory when it has no -/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per +/// `CMakeCache.txt` or no File API reply yet, then `cmake --build` (`--clean-first` to rebuild), one job per /// logical CPU unless the profile's build arguments choose a count. The directory and /// options come from the CMake profile; without one, a configured directory of the project /// (the first by name), else `build`, as the generated run configurations use. fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec { let build_dir = match profile { Some(p) if !p.build_dir.trim().is_empty() => p.build_dir.trim().to_owned(), + Some(p) if p.build_type.is_empty() => "cmake-build-default".into(), Some(p) => format!("cmake-build-{}", p.build_type.to_lowercase()), None => { let mut configured: Vec = std::fs::read_dir(dir) @@ -444,18 +445,49 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V let build_type = profile.map_or("Debug", |p| p.build_type.as_str()); let env = profile.map(|p| p.env.clone()).unwrap_or_default(); let mut steps = Vec::new(); - if !dir.join(&build_dir).join("CMakeCache.txt").is_file() { - let mut configure = BuildStep::new("cmake", &["-S", ".", "-B", &build_dir], dir, Format::Gcc); - if let Some(p) = profile.filter(|p| !p.generator.trim().is_empty()) { - configure.args.extend(["-G".into(), p.generator.clone()]); - } - configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}")); + let preset = profile.and_then(|p| p.preset.as_ref()); + // The profile's toolchain may bring its own cmake. + let cmake = profile.and_then(|p| p.cmake_program.as_ref()).map_or("cmake".into(), |c| c.to_string_lossy()); + let cmake = cmake.as_ref(); + let build_path = dir.join(&build_dir); + // Configured without the File API queries (by another tool, or before they were written): + // configure again so the targets, and their run configurations, become known. + let fresh = !build_path.join("CMakeCache.txt").is_file(); + if fresh || !build_path.join(ide_core::cmake_file_api::REPLY).is_dir() { + // Best effort: without the queries the build still runs, only the targets stay unknown. + let _ = ide_core::cmake_file_api::write_queries(&build_path); + let mut configure = match preset { + // The preset sets the generator and cache variables. + Some(preset) => BuildStep::new(cmake, &["--preset", &preset.configure], dir, Format::Gcc), + None => { + let mut configure = BuildStep::new(cmake, &["-S", ".", "-B", &build_dir], dir, Format::Gcc); + // A configured directory keeps its generator (CMake refuses another one) and, + // without a profile, its build type. + if let Some(p) = profile.filter(|p| fresh && !p.generator.trim().is_empty()) { + configure.args.extend(["-G".into(), p.generator.clone()]); + } + if fresh || profile.is_some() { + configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}")); + } + configure + } + }; configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into()); configure.args.extend(profile.map(|p| p.cmake_args.clone()).unwrap_or_default()); configure.env = env.clone(); steps.push(configure); } - let mut build = BuildStep::new("cmake", &["--build", &build_dir, "--config", build_type], dir, Format::Gcc); + let mut build = match preset.and_then(|p| p.build.as_deref()) { + Some(build) => BuildStep::new(cmake, &["--build", "--preset", build], dir, Format::Gcc), + None => { + let mut build = BuildStep::new(cmake, &["--build", &build_dir], dir, Format::Gcc); + // CLion's "Default" build type: no configuration at all. + if !build_type.is_empty() { + build.args.extend(["--config".into(), build_type.into()]); + } + build + } + }; if kind == BuildKind::Rebuild { build.args.push("--clean-first".into()); } @@ -1659,6 +1691,15 @@ mod tests { "an unconfigured project is configured first" ); write(&cm, "cmake-build-release/CMakeCache.txt", ""); + let p = + plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap(); + assert_eq!( + p.steps[0].args, + ["-S", ".", "-B", "cmake-build-release", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"], + "configured again, as it was, when it has no File API reply" + ); + assert!(cm.join("cmake-build-release/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file()); + std::fs::create_dir_all(cm.join("cmake-build-release").join(ide_core::cmake_file_api::REPLY)).unwrap(); let p = plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap(); assert_eq!( @@ -1694,6 +1735,33 @@ mod tests { ) .unwrap(); assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]); + let preset = CMakeProfile { + build_dir: "out/dev".into(), + preset: Some(ide_core::settings::CMakePresetRef { + configure: "dev".into(), + build: Some("dev-build".into()), + ..Default::default() + }), + ..CMakeProfile::default() + }; + let p = plan( + &cm, + &BuildModel::default(), + BuildKind::Build, + None, + Some(std::slice::from_ref(&preset)), + None, + &CancellationToken::new(), + ) + .unwrap(); + assert_eq!( + args(&p), + [ + "--preset dev -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(), + format!("--build --preset dev-build {jobs}") + ], + "a preset profile configures and builds with its presets" + ); let siblings = tmp.path().join("siblings"); write(&siblings, "core/pom.xml", "core"); diff --git a/crates/ide-core/src/cmake_file_api.rs b/crates/ide-core/src/cmake_file_api.rs new file mode 100644 index 000000000..95a180a34 --- /dev/null +++ b/crates/ide-core/src/cmake_file_api.rs @@ -0,0 +1,20 @@ +//! The CMake File API queries the IDE writes into a build directory, shared by the run +//! configurations (which read the replies) and Build Project (which configures). + +use std::path::Path; + +/// The objects asked for: targets, cache, toolchains and the CMake files. +pub const QUERIES: [&str; 4] = ["codemodel-v2", "cache-v2", "toolchains-v1", "cmakeFiles-v1"]; +const QUERY: &str = ".cmake/api/v1/query/client-openidea"; +/// Where CMake writes its replies, relative to the build directory. +pub const REPLY: &str = ".cmake/api/v1/reply"; + +/// Asks CMake to answer [`QUERIES`] on the next configure of `build`. +pub fn write_queries(build: &Path) -> std::io::Result<()> { + let query = build.join(QUERY); + std::fs::create_dir_all(&query)?; + for name in QUERIES { + std::fs::write(query.join(name), "")?; + } + Ok(()) +} diff --git a/crates/ide-core/src/lib.rs b/crates/ide-core/src/lib.rs index 7f9981bf8..b283d33d5 100644 --- a/crates/ide-core/src/lib.rs +++ b/crates/ide-core/src/lib.rs @@ -6,6 +6,7 @@ pub mod build_jobs; pub mod cli_process; +pub mod cmake_file_api; pub mod editor_settings; pub mod error; pub mod event; diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 3a4d59276..a42bcb40a 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -68,6 +68,8 @@ pub struct Settings { /// Build, Execution, Deployment › Run Targets. pub run_targets: Vec, pub cmake: CMakeSettings, + /// Build, Execution, Deployment › Toolchains; the first is the default. + pub toolchains: Vec, /// Settings › Agents. pub agents: AgentSettings, /// Agents › MCP Server (global only). @@ -750,9 +752,42 @@ impl Default for SettingsSyncSettings { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct CMakeSettings { - #[serde(skip_serializing_if = "Option::is_none")] + /// Serialized as `null` when absent, so `cmake.profiles` stays a known settings key. #[specta(optional)] pub profiles: Option>, + /// `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible + /// configure preset whose condition holds is listed after the explicit profiles. + pub ignore_presets: bool, + /// Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but + /// disabled until enabled here. + pub enabled_presets: Vec, + /// The profile (by name) that build, run and debug use, as CLion's toolbar switcher; + /// empty or unknown = the first enabled one. + pub active_profile: String, +} + +/// The presets a profile made from `CMakePresets.json` runs with. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(default, rename_all = "camelCase")] +pub struct CMakePresetRef { + pub configure: String, + /// The first build preset of `configure`, used by `cmake --build --preset`. + #[serde(skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub build: Option, + /// The first test preset of `configure`, used by `ctest --preset`. + #[serde(skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub test: Option, + /// Cache variables the resolved preset sets itself, read when presets are loaded (never + /// saved): a toolchain does not override them. + #[serde(skip)] + #[specta(skip)] + pub cache_variables: Vec, + /// The preset names a toolchain file, which picks the compilers. + #[serde(skip)] + #[specta(skip)] + pub toolchain_file: bool, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] @@ -766,6 +801,23 @@ pub struct CMakeProfile { pub build_dir: String, pub build_args: Vec, pub env: BTreeMap, + /// `false` keeps the profile listed but unused (CLion's "Enable profile"). + pub enabled: bool, + /// Toolchain name (Settings › Toolchains); empty = the default (first) toolchain. + pub toolchain: String, + /// Set only on the profiles made from presets: configure with `cmake --preset`, and the + /// generator and cache variables come from the preset. + #[serde(skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub preset: Option, + /// Resolved from the toolchain when profiles are put to use (never saved): the `cmake` + /// to run (`ctest` next to it) and the debugger to prefer. + #[serde(skip)] + #[specta(skip)] + pub cmake_program: Option, + #[serde(skip)] + #[specta(skip)] + pub debugger: Option, } impl Default for CMakeProfile { @@ -778,10 +830,44 @@ impl Default for CMakeProfile { build_dir: String::new(), build_args: Vec::new(), env: BTreeMap::new(), + enabled: true, + toolchain: String::new(), + preset: None, + cmake_program: None, + debugger: None, } } } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum ToolchainKind { + /// Tools from the chosen paths, else from `PATH`. + #[default] + System, + /// A MinGW / MSYS2 directory: its `bin` goes first on `PATH`, with gcc, g++, + /// mingw32-make and gdb from there. + #[serde(rename = "mingw")] + MinGw, +} + +/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are +/// detected: from the MinGW directory, else from `PATH`. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(default, rename_all = "camelCase")] +pub struct Toolchain { + pub name: String, + pub kind: ToolchainKind, + /// The MinGW directory (the one holding `bin`). + pub path: String, + pub cmake: String, + /// `CMAKE_MAKE_PROGRAM`: make, mingw32-make or ninja. + pub build_tool: String, + pub c_compiler: String, + pub cxx_compiler: String, + pub debugger: String, +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct ToolSettings { @@ -893,6 +979,7 @@ impl Default for Settings { deployment: DeploymentSettings::default(), run_targets: Vec::new(), cmake: CMakeSettings::default(), + toolchains: Vec::new(), agents: AgentSettings::default(), mcp_server: McpServerSettings::default(), agent_security: AgentSecuritySettings::default(), diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 0bd9ac674..733b241e7 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -1055,6 +1055,15 @@ impl DebugManager { if let Some(command) = custom_command(&spec.command) { spec.command = command; } + // The debugger of the run configuration's toolchain (a MinGW gdb), over every other choice. + if let Some(command) = arguments + .as_object_mut() + .and_then(|o| o.remove(native::ADAPTER_COMMAND)) + .and_then(|v| v.as_str().map(str::to_owned)) + { + spec.command = command; + spec.pinned = None; + } // debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy), // or with the launcher's when the debuggee runs through a manager (`uv run python`). if config.adapter == "debugpy" { diff --git a/crates/ide-dap/src/native.rs b/crates/ide-dap/src/native.rs index c74bfc793..6556e2594 100644 --- a/crates/ide-dap/src/native.rs +++ b/crates/ide-dap/src/native.rs @@ -8,6 +8,10 @@ use ide_core::{IdeError, IdeResult}; use serde_json::{Map, Value, json}; use std::path::{Path, PathBuf}; +/// Launch argument naming the debugger to run (a toolchain's gdb or lldb-dap), which replaces +/// the search: lldb-dap if its name says so, else GDB. +pub const ADAPTER_COMMAND: &str = "__adapterCommand"; + /// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it. pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found"; @@ -20,7 +24,16 @@ pub async fn choose( if config.adapter != "lldb-dap" || config.request != "launch" { return Ok(config); } + let chosen = config + .extra_json + .as_deref() + .and_then(|e| serde_json::from_str::(e).ok()) + .and_then(|e| e[ADAPTER_COMMAND].as_str().map(PathBuf::from)); let found = tokio::task::spawn_blocking(move || { + if let Some(chosen) = chosen { + let name = chosen.file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default(); + return if name.contains("lldb-dap") { Found::LldbDap } else { Found::Gdb(chosen) }; + } if lookup("lldb-dap").is_some() { return Found::LldbDap; } @@ -154,6 +167,19 @@ mod tests { assert_eq!(extra(&config)["swiftpm"]["product"], "app"); } + #[tokio::test] + async fn a_toolchain_debugger_replaces_the_search() { + let mut launch = cmake_launch(); + launch.extra_json = Some(json!({"env": ["A=1"], ADAPTER_COMMAND: "/opt/mingw/bin/gdb.exe"}).to_string()); + // lldb-dap is there, but the toolchain names its GDB (an unknown version is left to GDB). + let config = choose(launch, only(&["lldb-dap"])).await.unwrap(); + assert_eq!(config.adapter, "gdb"); + assert_eq!(extra(&config)[ADAPTER_COMMAND], "/opt/mingw/bin/gdb.exe", "kept for the adapter launch"); + let mut launch = cmake_launch(); + launch.extra_json = Some(json!({ADAPTER_COMMAND: "/opt/llvm/bin/lldb-dap"}).to_string()); + assert_eq!(choose(launch, only(&[])).await.unwrap().adapter, "lldb-dap"); + } + #[tokio::test] async fn without_any_debugger_says_what_to_install() { let e = choose(cmake_launch(), only(&[])).await.unwrap_err(); diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 12159473b..06704b5ef 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -201,6 +201,143 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult { blocking(move || workspace::load_project(&project, &config)).await } +/// Settings › CMake and the toolbar switcher: every profile, saved ones then presets (with +/// whether each is enabled), and why the presets file cannot be read, if it cannot. +#[derive(Clone, Debug, serde::Serialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct CMakeProfileList { + pub profiles: Vec, + pub presets_error: Option, +} + +/// Reading the profiles runs nothing, so an untrusted project lists them too. +#[command(trust = always)] +pub async fn cmake_profiles(host: &Host, window: &str) -> IdeResult { + let project = host.project(window)?; + let (root, settings) = (project.root.clone(), project.settings.effective()); + blocking(move || { + let presets_error = if settings.cmake.ignore_presets { None } else { ide_run::cmake_presets(&root).err() }; + Ok(CMakeProfileList { profiles: ide_run::cmake_listed_profiles(&root, &settings.cmake), presets_error }) + }) + .await +} + +/// Settings › CMake › Cache variables: the `CMakeCache.txt` of `build_dir` (relative to the +/// project, or absolute), empty while that directory is not configured. Reading runs nothing. +#[command(trust = always)] +pub async fn cmake_cache( + host: &Host, + window: &str, + build_dir: String, +) -> IdeResult> { + let root = host.project(window)?.root.clone(); + blocking(move || { + let cache = root.join(build_dir.trim()).join("CMakeCache.txt"); + Ok(std::fs::read_to_string(cache).map(|text| ide_run::cmake_cache::parse(&text)).unwrap_or_default()) + }) + .await +} + +/// One tool of a toolchain as Settings › Toolchains shows it: the executable used (chosen, from the +/// MinGW directory, else found on `PATH`) and its version, or why it cannot be used. +#[derive(Clone, Debug, Default, serde::Serialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct ToolCheck { + pub path: Option, + pub version: Option, + pub problem: Option, +} + +/// Each tool of a toolchain, keyed as the toolchain's fields (`cmake`, `buildTool`, `cCompiler`, +/// `cxxCompiler`, `debugger`). +pub type ToolchainCheck = std::collections::BTreeMap; + +async fn check_tool(path: Option) -> ToolCheck { + let Some(path) = path else { + return ToolCheck { problem: Some("Not found".into()), ..Default::default() }; + }; + let shown = Some(path.to_string_lossy().into_owned()); + if !path.is_file() { + return ToolCheck { path: shown, problem: Some("Not found".into()), ..Default::default() }; + } + let mut command = tokio::process::Command::new(&path); + command.arg("--version").stdin(std::process::Stdio::null()).kill_on_drop(true); + ide_core::process::prepare(command.as_std_mut()); + match tokio::time::timeout(std::time::Duration::from_secs(5), command.output()).await { + Ok(Ok(output)) => { + let text = String::from_utf8_lossy(&output.stdout).into_owned() + &String::from_utf8_lossy(&output.stderr); + let version = text.lines().map(str::trim).find(|l| !l.is_empty()).map(String::from); + ToolCheck { path: shown, version, problem: None } + } + Ok(Err(e)) => ToolCheck { path: shown, problem: Some(e.to_string()), ..Default::default() }, + Err(_) => ToolCheck { path: shown, problem: Some("No answer to --version".into()), ..Default::default() }, + } +} + +/// Settings › Toolchains: which executable each tool of `toolchain` resolves to, and its version. +/// Only `--version` runs; the settings are IDE-wide, so no project needs to be trusted. +#[command(trust = always)] +pub async fn toolchain_check(toolchain: ide_core::settings::Toolchain) -> IdeResult { + let tools = ide_run::cmake_toolchain::tools(&toolchain); + let chosen = |key: &str| -> Option { + match key { + "cmake" => tools.cmake.clone(), + "buildTool" => tools.build_tool.clone().map(Into::into), + "cCompiler" => tools.c_compiler.clone().map(Into::into), + "cxxCompiler" => tools.cxx_compiler.clone().map(Into::into), + _ => tools.debugger.clone(), + } + }; + let search = match &tools.path { + Some(bin) => std::env::join_paths( + std::iter::once(bin.clone()).chain(std::env::split_paths(&ide_core::tool_path::search_path())), + ) + .unwrap_or_else(|_| ide_core::tool_path::search_path()), + None => ide_core::tool_path::search_path(), + }; + let mut out = ToolchainCheck::new(); + for (key, names) in ide_run::cmake_toolchain::FALLBACKS { + let path = chosen(key) + .map(|p| { + // A bare name ("clang++") is looked up like CMake would. + if p.components().count() == 1 { + ide_core::process::find_executable(&p.to_string_lossy(), &search).unwrap_or(p) + } else { + p + } + }) + .or_else(|| names.iter().find_map(|n| ide_core::process::find_executable(n, &search))); + out.insert(key.into(), check_tool(path).await); + } + Ok(out) +} + +/// Settings › Toolchains: a toolchain for each MinGW / MSYS2 install found (Windows). +#[command(trust = always)] +pub async fn toolchains_detect() -> IdeResult> { + blocking(|| { + Ok(ide_run::cmake_toolchain::detect_mingw() + .into_iter() + .map(|dir| { + let name = match dir.parent().and_then(|p| p.file_name()) { + // MSYS2 environments: "MSYS2 ucrt64". + Some(parent) if parent.to_string_lossy().starts_with("msys") => { + format!("MSYS2 {}", dir.file_name().unwrap_or_default().to_string_lossy()) + } + _ => format!("MinGW ({})", dir.display()), + }; + ide_core::settings::Toolchain { + name, + kind: ide_core::settings::ToolchainKind::MinGw, + path: dir.to_string_lossy().into_owned(), + ..Default::default() + } + }) + .collect()) + }) + .await +} + fn linked_gradle_paths( root: &Path, settings: &ide_core::settings::GradleSettings, @@ -1023,7 +1160,7 @@ pub async fn build_run( &model, kind, file.as_deref(), - settings.cmake.profiles.as_deref(), + ide_run::cmake_profiles(&root, &settings.cmake, &settings.toolchains).as_deref(), None, &token, )?, @@ -1071,7 +1208,7 @@ pub async fn build_run( &model, kind, file.as_deref(), - settings.cmake.profiles.as_deref(), + ide_run::cmake_profiles(member, &settings.cmake, &settings.toolchains).as_deref(), None, &token, )?, @@ -1094,7 +1231,7 @@ pub async fn build_run( &model, kind, file.as_deref(), - settings.cmake.profiles.as_deref(), + ide_run::cmake_profiles(&root, &settings.cmake, &settings.toolchains).as_deref(), Some(&cache), &token, ) { @@ -1687,6 +1824,8 @@ ide_command::domain!( build_model, build_run, build_sync, + cmake_cache, + cmake_profiles, gradle_dependencies, gradle_link_projects, gradle_published_catalog, @@ -1696,4 +1835,6 @@ ide_command::domain!( maven_exclude_dependency, maven_goto_declaration, maven_managed_declarations, + toolchain_check, + toolchains_detect, ); diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 31abbd7a4..d16a39f65 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -93,14 +93,17 @@ fn detected_and_saved( .linked_projects .as_ref() .map(|_| ide_build::gradle::load_linked(root, &settings.languages.java.gradle)); - let mut detected = ide_run::detect_with_profiles(root, &excluded_poms, settings.cmake.profiles.as_deref()); + let (mut saved, mut suppressed) = (saved.to_vec(), suppressed.to_vec()); + ide_run::upgrade_cmake_profile_ids(root, &settings.cmake, &mut saved, &mut suppressed); + let mut detected = ide_run::detect_with_cmake(root, &excluded_poms, &settings.cmake, &settings.toolchains); + ide_run::refresh_saved_cmake_profiles(&mut saved, &detected); detected.extend(ide_run::detect_builds(root, &linked_build_dirs(root, settings, gradle.as_deref(), &detected))); let mut all: Vec = detected .into_iter() .filter(|d| !suppressed.contains(&d.id) && !saved.iter().any(|u| u.id == d.id)) .filter(|d| linked_config(root, gradle.as_deref(), &excluded_poms, d)) .collect(); - all.extend(saved.iter().cloned()); + all.extend(saved); for config in all.iter_mut().filter(|c| !matches!(c.kind.as_str(), "gradle" | "maven")) { ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(config), root, settings); } @@ -971,6 +974,60 @@ mod ownership_tests { container_python_path(&mut none, &["/elsewhere".into()], root); assert!(none.is_empty()); } + #[test] + fn saved_cmake_configs_follow_the_active_profile_and_keep_launch_customizations() { + use ide_core::settings::CMakeProfile; + + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + std::fs::write(root.join("CMakeLists.txt"), "project(app)").unwrap(); + let profile = |name: &str| { + let reply = root.join(name).join(".cmake/api/v1/reply"); + std::fs::create_dir_all(&reply).unwrap(); + std::fs::write( + reply.join("index-1.json"), + r#"{"objects":[{"kind":"codemodel","version":{"major":2},"jsonFile":"model.json"}]}"#, + ) + .unwrap(); + std::fs::write( + reply.join("model.json"), + r#"{"configurations":[{"name":"","targets":[{"jsonFile":"app.json"}]}]}"#, + ) + .unwrap(); + std::fs::write( + reply.join("app.json"), + r#"{"name":"app","type":"EXECUTABLE","artifacts":[{"path":"app"}]}"#, + ) + .unwrap(); + CMakeProfile { name: name.into(), build_dir: name.into(), ..Default::default() } + }; + let mut settings = ide_core::settings::Settings::default(); + settings.cmake.profiles = Some(vec![profile("first"), profile("second")]); + let mut saved = detected_and_saved(root, &settings, &[], &[]); + let app = saved.iter_mut().find(|c| c.id == "cmake:profile:target:app").unwrap(); + app.name = "Custom app".into(); + app.args.push("--custom".into()); + app.env.insert("APP_MODE".into(), "custom".into()); + app.extras.before_launch.push(ide_run::BeforeLaunchTask { + kind: "run".into(), + target: "user:prepare".into(), + ..Default::default() + }); + let tasks = app.extras.before_launch.clone(); + + settings.cmake.active_profile = "second".into(); + let configs = detected_and_saved(root, &settings, &saved, &[]); + let find = |id: &str| configs.iter().find(|c| c.id == id).unwrap(); + let app = find("cmake:profile:target:app"); + assert_eq!(Path::new(&app.command), root.join("second/app")); + assert_eq!(app.name, "Custom app"); + assert_eq!(app.args, ["--custom"]); + assert_eq!(app.env["APP_MODE"], "custom"); + assert_eq!(app.extras.before_launch, tasks); + assert_eq!(find("cmake:profile:target:app:build").args[1], "second"); + assert_eq!(find("cmake:profile:configure").extras.params["buildDir"], "second"); + } + #[test] fn unlinked_builds_do_not_reappear_as_detected_application_configs() { let temp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-run/Cargo.toml b/crates/ide-run/Cargo.toml index 8ade7f198..78974e6c2 100644 --- a/crates/ide-run/Cargo.toml +++ b/crates/ide-run/Cargo.toml @@ -14,6 +14,7 @@ dunce.workspace = true encoding_rs.workspace = true serde.workspace = true serde_json.workspace = true +regex.workspace = true specta.workspace = true toml.workspace = true toml_edit.workspace = true diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index e31f16232..986fd11f6 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -29,6 +29,27 @@ pub(crate) fn detect_with_profiles( root: &Path, excluded_poms: &[PathBuf], profiles: Option<&[ide_core::settings::CMakeProfile]>, +) -> Vec { + detect_with_cmake_settings(root, excluded_poms, profiles, None) +} + +/// The root CMake project uses the settings' profiles and its presets; nested CMake projects +/// (a folder of several repositories) use their own presets, filtered by the same settings. +pub(crate) fn detect_with_cmake( + root: &Path, + excluded_poms: &[PathBuf], + settings: &ide_core::settings::CMakeSettings, + toolchains: &[ide_core::settings::Toolchain], +) -> Vec { + let profiles = cmake::presets::profiles(root, settings, toolchains); + detect_with_cmake_settings(root, excluded_poms, profiles.as_deref(), Some((settings, toolchains))) +} + +fn detect_with_cmake_settings( + root: &Path, + excluded_poms: &[PathBuf], + profiles: Option<&[ide_core::settings::CMakeProfile]>, + cmake_settings: Option<(&ide_core::settings::CMakeSettings, &[ide_core::settings::Toolchain])>, ) -> Vec { let mut out = Vec::new(); detect_node(root, &mut out); @@ -71,7 +92,16 @@ pub(crate) fn detect_with_profiles( ); for dir in ide_core::project_roots::discover(root, &["CMakeLists.txt"]) { let start = out.len(); - cmake::detect(&dir, if dir == root { profiles } else { None }, &mut out); + if dir == root { + cmake::detect(&dir, profiles, &mut out); + } else { + // The settings' own profiles describe the root project's build directories only. + let nested = cmake_settings.and_then(|(settings, toolchains)| { + let presets_only = ide_core::settings::CMakeSettings { profiles: None, ..settings.clone() }; + cmake::presets::profiles(&dir, &presets_only, toolchains) + }); + cmake::detect(&dir, nested.as_deref(), &mut out); + } if dir != root { let scope = Scope::new(root, &dir); for config in &mut out[start..] { diff --git a/crates/ide-run/src/detect/cmake.rs b/crates/ide-run/src/detect/cmake.rs deleted file mode 100644 index 0d7ee4274..000000000 --- a/crates/ide-run/src/detect/cmake.rs +++ /dev/null @@ -1,440 +0,0 @@ -//! CMake targets come from the File API codemodel, including evaluated subdirectories. - -use super::{ConfigExt, config}; -use crate::{BeforeLaunchTask, RunConfig}; -use ide_core::build_jobs::append_default_jobs; -use ide_core::settings::CMakeProfile; -use serde_json::Value; -use std::fs; -use std::path::{Path, PathBuf}; - -fn json(path: &Path) -> Option { - serde_json::from_slice(&fs::read(path).ok()?).ok() -} - -fn reply_file(reply: &Path, name: &str) -> Option { - // File API references are file names, never paths outside the reply directory. - (Path::new(name).components().count() == 1).then(|| json(&reply.join(name))).flatten() -} - -fn before(config: &mut RunConfig, id: &str) { - config.extras.before_launch.push(BeforeLaunchTask { - kind: "build".into(), - target: id.into(), - ..Default::default() - }); -} - -#[derive(Default)] -struct Names { - contexts: Vec<(String, String)>, -} - -impl Names { - fn push(&mut self, out: &mut Vec, config: RunConfig, dir: &str, profile: &str) { - self.contexts.push((dir.replace('\\', "/"), profile.into())); - out.push(config); - } - - fn apply(self, configs: &mut [RunConfig]) { - let names: Vec<_> = configs.iter().map(|c| c.name.clone()).collect(); - for (index, config) in configs.iter_mut().enumerate() { - let duplicates: Vec<_> = names.iter().enumerate().filter(|(_, name)| **name == names[index]).collect(); - if duplicates.len() < 2 { - continue; - } - let (dir, profile) = &self.contexts[index]; - let needs_dir = duplicates.iter().any(|(other, _)| *other != index && self.contexts[*other].1 == *profile); - let mut context = Vec::new(); - if !profile.is_empty() { - context.push(profile.clone()); - } - if needs_dir { - context.push(format!("{}/", dir.trim_end_matches('/'))); - } - if !context.is_empty() { - config.name = format!("{} [{}]", config.name, context.join(" · ")); - } - } - } -} - -pub(super) fn detect(root: &Path, profiles: Option<&[CMakeProfile]>, out: &mut Vec) { - let start = out.len(); - let mut names = Names::default(); - detect_configs(root, profiles, out, &mut names); - names.apply(&mut out[start..]); -} - -fn detect_configs(root: &Path, profiles: Option<&[CMakeProfile]>, out: &mut Vec, names: &mut Names) { - if !root.join("CMakeLists.txt").is_file() { - return; - } - if let Some(profiles) = profiles { - for (index, profile) in profiles.iter().enumerate() { - detect_profile(root, profile, index, out, names); - } - return; - } - let mut builds = Vec::new(); - if let Ok(entries) = fs::read_dir(root) { - builds.extend(entries.flatten().filter_map(|e| { - let p = e.path(); - (p.is_dir() && p.join("CMakeCache.txt").is_file()).then_some(p) - })); - } - if builds.is_empty() { - builds.push(root.join("build")); - } - builds.sort(); - builds.dedup(); - for build in builds { - let dir = build.strip_prefix(root).unwrap_or(&build).to_string_lossy().replace('\\', "/"); - let configuration = fs::read_to_string(build.join("CMakeCache.txt")) - .ok() - .and_then(|cache| { - let values = cache.lines().find_map(|line| line.strip_prefix("CMAKE_CONFIGURATION_TYPES:STRING="))?; - Some(if values.split(';').any(|c| c == "Debug") { - "Debug".to_owned() - } else { - values.split(';').find(|s| !s.is_empty())?.to_owned() - }) - }) - .unwrap_or_else(|| "Debug".into()); - let prefix = format!("cmake:{dir}"); - let configure_id = format!("{prefix}:configure"); - let build_id = format!("{prefix}:build"); - let mut args = vec!["-S", ".", "-B", &dir, "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"]; - if !build.join("CMakeCache.txt").is_file() { - args.push("-DCMAKE_BUILD_TYPE=Debug"); - } - let mut configure = config(&configure_id, "CMake Configure", "cmake", "cmake", &args); - configure.extras.params.insert("buildDir".into(), dir.clone()); - names.push(out, configure, &dir, ""); - let mut all = - config(&build_id, "CMake Build", "cmake", "cmake", &["--build", &dir, "--config", &configuration]); - append_default_jobs(&mut all.args); - // `cmake --build` regenerates by itself once a build directory is configured. - if !build.join("CMakeCache.txt").is_file() { - before(&mut all, &configure_id); - } - names.push(out, all, &dir, ""); - let mut test = config( - format!("{prefix}:test"), - "CTest", - "cmake", - "ctest", - &["--test-dir", &dir, "-C", &configuration, "--output-on-failure"], - ); - before(&mut test, &build_id); - names.push(out, test, &dir, ""); - targets(root, &build, &dir, &prefix, None, out, names); - } -} - -fn detect_profile(root: &Path, profile: &CMakeProfile, index: usize, out: &mut Vec, names: &mut Names) { - let dir = if profile.build_dir.trim().is_empty() { - format!("cmake-build-{}", profile.build_type.to_lowercase()) - } else { - profile.build_dir.clone() - }; - let build = root.join(&dir); - let prefix = format!("cmake:profile:{index}"); - let configure_id = format!("{prefix}:configure"); - let build_id = format!("{prefix}:build"); - let start = out.len(); - let mut configure = config(&configure_id, "CMake Configure", "cmake", "cmake", &["-S", ".", "-B", &dir]); - if !profile.generator.trim().is_empty() { - configure.args.extend(["-G".into(), profile.generator.clone()]); - } - configure.args.push(format!("-DCMAKE_BUILD_TYPE={}", profile.build_type)); - configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into()); - configure.args.extend_from_slice(&profile.cmake_args); - configure.extras.params.insert("buildDir".into(), dir.clone()); - names.push(out, configure, &dir, &profile.name); - let mut all = - config(&build_id, "CMake Build", "cmake", "cmake", &["--build", &dir, "--config", &profile.build_type]); - all.args.extend_from_slice(&profile.build_args); - append_default_jobs(&mut all.args); - if !build.join("CMakeCache.txt").is_file() { - before(&mut all, &configure_id); - } - names.push(out, all, &dir, &profile.name); - let mut test = config( - format!("{prefix}:test"), - "CTest", - "cmake", - "ctest", - &["--test-dir", &dir, "-C", &profile.build_type, "--output-on-failure"], - ); - before(&mut test, &build_id); - names.push(out, test, &dir, &profile.name); - targets(root, &build, &dir, &prefix, Some(profile), out, names); - for config in &mut out[start..] { - config.env = profile.env.clone(); - } -} - -fn targets( - root: &Path, - build: &Path, - dir: &str, - prefix: &str, - profile: Option<&CMakeProfile>, - out: &mut Vec, - names: &mut Names, -) { - let reply = build.join(".cmake/api/v1/reply"); - let Some(index_path) = fs::read_dir(&reply).ok().and_then(|entries| { - entries - .flatten() - .map(|e| e.path()) - .filter(|p| { - let name = p.file_name().unwrap_or_default().to_string_lossy(); - name.starts_with("index-") && name.ends_with(".json") - }) - .max() - }) else { - return; - }; - let Some(index) = json(&index_path) else { return }; - let Some(reference) = index["objects"] - .as_array() - .and_then(|a| a.iter().find(|o| o["kind"] == "codemodel" && o["version"]["major"] == 2)) - else { - return; - }; - let Some(model) = reference["jsonFile"].as_str().and_then(|n| reply_file(&reply, n)) else { return }; - let Some(configurations) = model["configurations"].as_array() else { return }; - let source_root = model["paths"]["source"].as_str().map(PathBuf::from).unwrap_or_else(|| root.into()); - if source_root.canonicalize().ok() != root.canonicalize().ok() { - return; - } - let source_root = dunce::canonicalize(&source_root).unwrap_or(source_root); - for configuration in configurations { - let name = configuration["name"].as_str().unwrap_or(""); - if profile.is_some_and(|p| !name.is_empty() && name != p.build_type) { - continue; - } - let Some(targets) = configuration["targets"].as_array() else { continue }; - for target in targets { - let Some(target) = target["jsonFile"].as_str().and_then(|n| reply_file(&reply, n)) else { continue }; - if target["type"] != "EXECUTABLE" { - continue; - } - let (Some(target_name), Some(artifact)) = - (target["name"].as_str(), target["artifacts"][0]["path"].as_str()) - else { - continue; - }; - let id = format!("{prefix}:{name}:{target_name}"); - let target_build_id = format!("{id}:build"); - let mut args = vec!["--build", dir, "--target", target_name]; - if !name.is_empty() { - args.extend(["--config", name]); - } - let mut build_config = config(&target_build_id, format!("Build {target_name}"), "cmake", "cmake", &args); - if let Some(profile) = profile { - if name.is_empty() { - build_config.args.extend(["--config".into(), profile.build_type.clone()]); - } - build_config.args.extend_from_slice(&profile.build_args); - if !build.join("CMakeCache.txt").is_file() { - before(&mut build_config, &format!("{prefix}:configure")); - } - } - append_default_jobs(&mut build_config.args); - let label = profile.map_or(name, |p| p.name.as_str()); - names.push(out, build_config, dir, label); - let binary = build.join(artifact); - let mut run = - config(&id, target_name, "cmake-application", &binary.to_string_lossy(), &[]).debug("lldb-dap"); - before(&mut run, &target_build_id); - let sources: Vec = target["sources"] - .as_array() - .into_iter() - .flatten() - .filter_map(|s| { - let p = source_root.join(s["path"].as_str()?); - Some(p.to_string_lossy().replace('\\', "/")) - }) - .collect(); - run.extras.params.insert("cmakeSources".into(), sources.join("\n")); - if let Some(recorded) = model["paths"]["source"].as_str() { - run.extras.params.insert("cmakeSourceRoot".into(), recorded.into()); - run.extras - .params - .insert("cmakeCanonicalSourceRoot".into(), source_root.to_string_lossy().replace('\\', "/")); - } - names.push(out, run, dir, label); - } - } -} - -/// Ordered configure/build commands for a CMake build configuration. Executables and CTest -/// are never executed by Build; only their explicit build prerequisites are accepted. -pub fn build_configs(configs: &[RunConfig], id: &str) -> crate::IdeResult> { - fn visit( - configs: &[RunConfig], - id: &str, - chain: &mut Vec, - out: &mut Vec, - ) -> crate::IdeResult<()> { - if chain.iter().any(|entry| entry == id) { - return Err(ide_core::IdeError::invalid("The before launch tasks run in a cycle")); - } - let config = configs - .iter() - .find(|c| c.id == id) - .ok_or_else(|| ide_core::IdeError::not_found(format!("Configuration '{id}' no longer exists")))?; - if config.kind != "cmake" || !config.args.first().is_some_and(|a| a == "--build" || a == "-S") { - return Err(ide_core::IdeError::invalid("Not a CMake configure or build configuration")); - } - chain.push(id.into()); - for task in &config.extras.before_launch { - if !matches!(task.kind.as_str(), "run" | "build") || task.target.is_empty() { - return Err(ide_core::IdeError::invalid("CMake builds require configure/build prerequisites")); - } - visit(configs, &task.target, chain, out)?; - } - chain.pop(); - if !out.iter().any(|c| c.id == id) { - out.push(config.clone()); - } - Ok(()) - } - let mut out = Vec::new(); - visit(configs, id, &mut Vec::new(), &mut out)?; - Ok(out) -} - -/// Request the codemodel when executing a configure configuration. -pub fn prepare(config: &RunConfig, cwd: &Path) -> crate::IdeResult<()> { - if config.kind == "cmake" - && config.args.first().is_some_and(|a| a == "-S") - && let Some(dir) = config.extras.params.get("buildDir") - { - let build = cwd.join(dir); - let generator = config.args.windows(2).find(|a| a[0] == "-G").map(|a| a[1].as_str()); - if let Some(generator) = generator - && let Ok(cache) = fs::read_to_string(build.join("CMakeCache.txt")) - && let Some(cached) = cache.lines().find_map(|l| l.strip_prefix("CMAKE_GENERATOR:INTERNAL=")) - && cached != generator - { - fs::remove_file(build.join("CMakeCache.txt"))?; - let files = build.join("CMakeFiles"); - if files.is_dir() { - fs::remove_dir_all(files)?; - } - } - let query = build.join(".cmake/api/v1/query/client-openidea"); - fs::create_dir_all(&query)?; - fs::write(query.join("codemodel-v2"), "")?; - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn profiles_select_file_api_configuration_and_apply_target_options() { - let root = tempfile::tempdir().unwrap(); - fs::write(root.path().join("CMakeLists.txt"), "project(app)").unwrap(); - let reply = root.path().join("output/.cmake/api/v1/reply"); - fs::create_dir_all(&reply).unwrap(); - let write = |name: &str, value: Value| fs::write(reply.join(name), value.to_string()).unwrap(); - write( - "index-1.json", - serde_json::json!({"objects":[{"kind":"codemodel","version":{"major":2},"jsonFile":"model.json"}]}), - ); - write( - "model.json", - serde_json::json!({"paths":{"source":root.path()},"configurations":[ - {"name":"Debug","targets":[{"jsonFile":"debug.json"}]}, - {"name":"Release","targets":[{"jsonFile":"release.json"}]} - ]}), - ); - for name in ["debug", "release"] { - write( - &format!("{name}.json"), - serde_json::json!({"name":"app","type":"EXECUTABLE","artifacts":[{"path":format!("{name}/app")}]}), - ); - } - let profile = CMakeProfile { - name: "Production".into(), - build_type: "Release".into(), - build_dir: "output".into(), - build_args: ["-j", "8", "--", "verbose=1"].map(String::from).into(), - env: [("FOO".into(), "bar".into())].into(), - ..Default::default() - }; - let mut configs = Vec::new(); - detect(root.path(), Some(std::slice::from_ref(&profile)), &mut configs); - let run = configs.iter().find(|c| c.kind == "cmake-application").unwrap(); - assert!(run.command.ends_with("release/app")); - assert_eq!(run.env, profile.env); - assert_eq!(configs.iter().filter(|c| c.kind == "cmake-application").count(), 1); - let build = configs.iter().find(|c| c.id == run.extras.before_launch[0].target).unwrap(); - assert_eq!( - build.args, - ["--build", "output", "--target", "app", "--config", "Release", "-j", "8", "--", "verbose=1"] - ); - assert_eq!(build.env, profile.env); - assert_eq!(build.extras.before_launch[0].target, "cmake:profile:0:configure"); - fs::write(root.path().join("output/CMakeCache.txt"), "CMAKE_GENERATOR:INTERNAL=Ninja\n").unwrap(); - let mut configured = Vec::new(); - detect(root.path(), Some(std::slice::from_ref(&profile)), &mut configured); - for id in ["cmake:profile:0:build", build.id.as_str()] { - let build = configured.iter().find(|c| c.id == id).unwrap(); - assert!(build.extras.before_launch.is_empty(), "{id} should use CMake's automatic regeneration"); - } - } - - #[test] - fn build_dependencies_are_scoped_and_reject_cycles_or_executables() { - let root = tempfile::tempdir().unwrap(); - let nested = root.path().join("nested"); - fs::create_dir_all(&nested).unwrap(); - fs::write(nested.join("CMakeLists.txt"), "project(app)").unwrap(); - let configs = crate::detect(root.path()); - let build = configs.iter().find(|c| c.args.first().is_some_and(|a| a == "--build")).unwrap(); - assert_eq!(build.extras.before_launch[0].kind, "build"); - let ordered = build_configs(&configs, &build.id).unwrap(); - assert_eq!(ordered.len(), 2); - assert_eq!(ordered[0].args[0], "-S"); - assert_eq!(ordered[1].args[0], "--build"); - assert_eq!(ordered[1].cwd, build.cwd); - assert!(build_configs(&configs, "missing").is_err()); - let mut cycle = configs.clone(); - let configure = cycle.iter_mut().find(|c| c.id == ordered[0].id).unwrap(); - before(configure, &build.id); - assert!(build_configs(&cycle, &build.id).is_err()); - for kind in ["native", "cmake-application", "shell"] { - let mut invalid = build.clone(); - invalid.kind = kind.into(); - assert!(build_configs(&[invalid.clone()], &invalid.id).is_err()); - } - let test = configs.iter().find(|c| c.command == "ctest").unwrap(); - assert!(build_configs(&configs, &test.id).is_err()); - } - - #[test] - fn generator_change_clears_only_cmake_state_at_launch() { - let root = tempfile::tempdir().unwrap(); - let build = root.path().join("cmake-build-debug"); - fs::create_dir_all(build.join("CMakeFiles")).unwrap(); - fs::write(build.join("CMakeCache.txt"), "CMAKE_GENERATOR:INTERNAL=Unix Makefiles\n").unwrap(); - fs::write(build.join("keep.txt"), "artifact").unwrap(); - fs::write(root.path().join("CMakeLists.txt"), "project(app)").unwrap(); - let mut configs = Vec::new(); - detect(root.path(), Some(&[CMakeProfile { generator: "Ninja".into(), ..Default::default() }]), &mut configs); - assert!(build.join("CMakeCache.txt").exists()); - prepare(&configs[0], root.path()).unwrap(); - assert!(!build.join("CMakeCache.txt").exists()); - assert!(!build.join("CMakeFiles").exists()); - assert!(build.join("keep.txt").exists()); - assert!(build.join(".cmake/api/v1/query/client-openidea/codemodel-v2").exists()); - } -} diff --git a/crates/ide-run/src/detect/cmake/cache.rs b/crates/ide-run/src/detect/cmake/cache.rs new file mode 100644 index 000000000..0e8298189 --- /dev/null +++ b/crates/ide-run/src/detect/cmake/cache.rs @@ -0,0 +1,87 @@ +//! `CMakeCache.txt` as Settings › CMake shows it (CLion's "Cache variables"): the user-visible +//! entries with their type, value, help text and whether CMake marks them advanced. + +use std::collections::HashSet; + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct CacheEntry { + pub name: String, + /// `BOOL`, `STRING`, `PATH`, `FILEPATH`… + pub kind: String, + pub value: String, + pub help: String, + pub advanced: bool, +} + +/// The entries of a `CMakeCache.txt`, in file order. `INTERNAL` and `STATIC` entries are CMake's +/// own bookkeeping and are left out, as CLion does. +pub fn parse(text: &str) -> Vec { + let mut help = Vec::new(); + let mut entries = Vec::new(); + let mut advanced = HashSet::new(); + for line in text.lines() { + let line = line.trim_end_matches('\r'); + if let Some(comment) = line.strip_prefix("//") { + help.push(comment.trim().to_owned()); + continue; + } + if line.is_empty() || line.starts_with('#') { + help.clear(); + continue; + } + let Some((key, value)) = line.split_once('=') else { continue }; + // A quoted name may hold a colon: "NAME:WITH:COLONS":TYPE=value. + let (name, kind) = match key.strip_prefix('"').and_then(|k| k.split_once("\":")) { + Some((name, kind)) => (name, kind), + None => match key.rsplit_once(':') { + Some(pair) => pair, + None => continue, + }, + }; + if let Some(of) = name.strip_suffix("-ADVANCED") { + if value == "1" { + advanced.insert(of.to_owned()); + } + } else if kind != "INTERNAL" && kind != "STATIC" { + entries.push(CacheEntry { + name: name.into(), + kind: kind.into(), + value: value.into(), + help: help.join(" "), + advanced: false, + }); + } + help.clear(); + } + for entry in &mut entries { + entry.advanced = advanced.contains(&entry.name); + } + entries +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_user_entries_with_help_and_advanced_flags() { + let text = "# This is the CMakeCache file.\n\n\ + //Choose the type of build.\n//Second line.\nCMAKE_BUILD_TYPE:STRING=Debug\n\n\ + //Path to a program.\nCMAKE_AR:FILEPATH=/usr/bin/ar\n\n\ + //No help, variable specified on the command line.\n\"WEIRD:NAME\":BOOL=ON\n\n\ + ########################\n# INTERNAL cache entries\n########################\n\n\ + //ADVANCED property for variable: CMAKE_AR\nCMAKE_AR-ADVANCED:INTERNAL=1\n\ + CMAKE_CACHEFILE_DIR:INTERNAL=/build\nCMAKE_HOME:STATIC=/src\n"; + let entries = parse(text); + assert_eq!( + entries.iter().map(|e| e.name.as_str()).collect::>(), + ["CMAKE_BUILD_TYPE", "CMAKE_AR", "WEIRD:NAME"] + ); + assert_eq!(entries[0].help, "Choose the type of build. Second line."); + assert_eq!((entries[0].kind.as_str(), entries[0].value.as_str()), ("STRING", "Debug")); + assert!(!entries[0].advanced); + assert!(entries[1].advanced); + assert_eq!(entries[2].kind, "BOOL"); + } +} diff --git a/crates/ide-run/src/detect/cmake/file_api.rs b/crates/ide-run/src/detect/cmake/file_api.rs new file mode 100644 index 000000000..3830ea6cf --- /dev/null +++ b/crates/ide-run/src/detect/cmake/file_api.rs @@ -0,0 +1,342 @@ +//! Typed reader for the CMake File API reply of one build directory. +//! +//! The IDE writes its queries (see [`write_queries`]) before every configure, and CMake answers +//! in `/.cmake/api/v1/reply`. Reading never fails: a missing, stale or malformed reply +//! simply yields `None` or empty collections, because detection must keep working on projects +//! that were never configured. + +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use ide_core::cmake_file_api::REPLY; +/// Objects the IDE asks for: targets (codemodel), cache variables (Qt detection reads +/// `Qt6_DIR`/`CMAKE_PREFIX_PATH`), compilers (toolchains) and the CMake input files. +pub use ide_core::cmake_file_api::{QUERIES, write_queries}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TargetKind { + Executable, + StaticLibrary, + SharedLibrary, + ModuleLibrary, + ObjectLibrary, + InterfaceLibrary, + Utility, +} + +impl TargetKind { + fn parse(value: &str) -> Option { + Some(match value { + "EXECUTABLE" => Self::Executable, + "STATIC_LIBRARY" => Self::StaticLibrary, + "SHARED_LIBRARY" => Self::SharedLibrary, + "MODULE_LIBRARY" => Self::ModuleLibrary, + "OBJECT_LIBRARY" => Self::ObjectLibrary, + "INTERFACE_LIBRARY" => Self::InterfaceLibrary, + "UTILITY" => Self::Utility, + _ => return None, + }) + } + + /// CMake's own name for the type (`EXECUTABLE`, `STATIC_LIBRARY`…), as the File API spells it. + pub fn as_str(self) -> &'static str { + match self { + Self::Executable => "EXECUTABLE", + Self::StaticLibrary => "STATIC_LIBRARY", + Self::SharedLibrary => "SHARED_LIBRARY", + Self::ModuleLibrary => "MODULE_LIBRARY", + Self::ObjectLibrary => "OBJECT_LIBRARY", + Self::InterfaceLibrary => "INTERFACE_LIBRARY", + Self::Utility => "UTILITY", + } + } + + /// Libraries that produce something when built. Interface libraries have nothing to build. + pub fn is_buildable_library(self) -> bool { + matches!(self, Self::StaticLibrary | Self::SharedLibrary | Self::ModuleLibrary | Self::ObjectLibrary) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CompileGroup { + pub language: String, + pub includes: Vec, + pub defines: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Target { + /// Unique within a configuration; what `dependencies` refer to. + pub id: String, + pub name: String, + pub kind: TargetKind, + /// Paths relative to the build directory (or absolute), as CMake reports them. + pub artifacts: Vec, + /// Paths relative to the source root (or absolute), as CMake reports them. + pub sources: Vec, + pub dependencies: Vec, + pub compile_groups: Vec, + /// Targets CMake adds by itself, such as `ZERO_CHECK` and `ALL_BUILD` with Visual Studio. + pub generator_provided: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Configuration { + /// Empty for single-config generators that were configured without `CMAKE_BUILD_TYPE`. + pub name: String, + pub targets: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CodeModel { + /// The source directory recorded at configure time. + pub source: Option, + pub configurations: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Toolchain { + pub language: String, + pub compiler: Option, + pub id: Option, + pub version: Option, +} + +/// The newest reply of one build directory. +pub struct Reply { + dir: PathBuf, + index: Value, +} + +/// The latest reply index of `build`, if CMake ever answered there. +pub fn read(build: &Path) -> Option { + let dir = build.join(REPLY); + // Index names embed a timestamp, so the lexicographically greatest one is the newest. + let index = fs::read_dir(&dir) + .ok()? + .flatten() + .map(|e| e.path()) + .filter(|p| { + let name = p.file_name().unwrap_or_default().to_string_lossy(); + name.starts_with("index-") && name.ends_with(".json") + }) + .max()?; + Some(Reply { index: json(&index)?, dir }) +} + +fn json(path: &Path) -> Option { + serde_json::from_slice(&fs::read(path).ok()?).ok() +} + +fn strings(values: &Value, key: &str) -> Vec { + values.as_array().into_iter().flatten().filter_map(|v| v[key].as_str().map(String::from)).collect() +} + +impl Reply { + fn file(&self, name: &str) -> Option { + // File API references are file names, never paths outside the reply directory. + (Path::new(name).components().count() == 1).then(|| json(&self.dir.join(name))).flatten() + } + + fn object(&self, kind: &str, major: u64) -> Option { + let reference = + self.index["objects"].as_array()?.iter().find(|o| o["kind"] == kind && o["version"]["major"] == major)?; + self.file(reference["jsonFile"].as_str()?) + } + + pub fn codemodel(&self) -> Option { + let model = self.object("codemodel", 2)?; + let configurations = model["configurations"] + .as_array()? + .iter() + .map(|configuration| Configuration { + name: configuration["name"].as_str().unwrap_or_default().into(), + targets: configuration["targets"] + .as_array() + .into_iter() + .flatten() + .filter_map(|t| self.target(t["jsonFile"].as_str()?)) + .collect(), + }) + .collect(); + Some(CodeModel { source: model["paths"]["source"].as_str().map(PathBuf::from), configurations }) + } + + fn target(&self, file: &str) -> Option { + let target = self.file(file)?; + let sources = target["sources"].as_array().map(Vec::as_slice).unwrap_or_default(); + Some(Target { + id: target["id"].as_str().unwrap_or_default().into(), + name: target["name"].as_str()?.into(), + kind: TargetKind::parse(target["type"].as_str()?)?, + artifacts: strings(&target["artifacts"], "path"), + sources: sources.iter().filter_map(|s| s["path"].as_str().map(String::from)).collect(), + dependencies: strings(&target["dependencies"], "id"), + compile_groups: target["compileGroups"] + .as_array() + .into_iter() + .flatten() + .map(|group| CompileGroup { + language: group["language"].as_str().unwrap_or_default().into(), + includes: strings(&group["includes"], "path").into_iter().map(PathBuf::from).collect(), + defines: strings(&group["defines"], "define"), + }) + .collect(), + generator_provided: target["isGeneratorProvided"].as_bool().unwrap_or(false), + }) + } + + /// Cache variables by name, with their values as CMake stores them (lists stay `;`-joined). + pub fn cache(&self) -> BTreeMap { + let Some(cache) = self.object("cache", 2) else { return BTreeMap::new() }; + cache["entries"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| Some((e["name"].as_str()?.into(), e["value"].as_str()?.into()))) + .collect() + } + + pub fn toolchains(&self) -> Vec { + let Some(toolchains) = self.object("toolchains", 1) else { return Vec::new() }; + toolchains["toolchains"] + .as_array() + .into_iter() + .flatten() + .filter_map(|t| { + let compiler = &t["compiler"]; + Some(Toolchain { + language: t["language"].as_str()?.into(), + compiler: compiler["path"].as_str().map(PathBuf::from), + id: compiler["id"].as_str().map(String::from), + version: compiler["version"].as_str().map(String::from), + }) + }) + .collect() + } + + /// The project's own CMake inputs (CMakeLists.txt, included `.cmake` files), relative to + /// the source root or absolute; generated and external files (CMake's modules) are skipped. + pub fn cmake_files(&self) -> Vec { + let Some(files) = self.object("cmakeFiles", 1) else { return Vec::new() }; + files["inputs"] + .as_array() + .into_iter() + .flatten() + .filter(|i| !i["isGenerated"].as_bool().unwrap_or(false) && !i["isExternal"].as_bool().unwrap_or(false)) + .filter_map(|i| i["path"].as_str().map(String::from)) + .collect() + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use serde_json::json; + + /// Writes a reply with an index pointing at `objects` (`(kind, major, file, value)`) and any + /// extra files, as CMake would. + pub(crate) fn write_reply(build: &Path, objects: &[(&str, u64, &str, Value)], files: &[(&str, Value)]) { + let reply = build.join(REPLY); + fs::create_dir_all(&reply).unwrap(); + let index: Vec<_> = objects + .iter() + .map(|(kind, major, file, _)| json!({"kind": kind, "version": {"major": major}, "jsonFile": file})) + .collect(); + fs::write(reply.join("index-1.json"), json!({ "objects": index }).to_string()).unwrap(); + for (_, _, file, value) in objects { + fs::write(reply.join(file), value.to_string()).unwrap(); + } + for (file, value) in files { + fs::write(reply.join(file), value.to_string()).unwrap(); + } + } + + #[test] + fn reads_targets_cache_toolchains_and_inputs() { + let build = tempfile::tempdir().unwrap(); + write_reply( + build.path(), + &[ + ( + "codemodel", + 2, + "model.json", + json!({"paths": {"source": "/src"}, "configurations": [{"name": "Debug", "targets": [ + {"jsonFile": "app.json"}, {"jsonFile": "core.json"}, {"jsonFile": "../escape.json"}, + {"jsonFile": "weird.json"} + ]}]}), + ), + ( + "cache", + 2, + "cache.json", + json!({"entries": [{"name": "Qt6_DIR", "value": "C:/Qt/6.8.0/msvc2022_64/lib/cmake/Qt6"}]}), + ), + ( + "toolchains", + 1, + "toolchains.json", + json!({"toolchains": [{"language": "CXX", "compiler": {"path": "/usr/bin/c++", "id": "GNU", "version": "14.2"}}]}), + ), + ( + "cmakeFiles", + 1, + "files.json", + json!({"inputs": [ + {"path": "CMakeLists.txt"}, {"path": "/usr/share/cmake/Modules/X.cmake", "isExternal": true}, + {"path": "build/gen.cmake", "isGenerated": true}, {"path": "cmake/deps.cmake"} + ]}), + ), + ], + &[ + ( + "app.json", + json!({"id": "app::@1", "name": "app", "type": "EXECUTABLE", "artifacts": [{"path": "app"}], + "sources": [{"path": "main.cpp"}], "dependencies": [{"id": "core::@1"}], + "compileGroups": [{"language": "CXX", "includes": [{"path": "/src/include"}], + "defines": [{"define": "QT_CORE_LIB"}]}]}), + ), + ("core.json", json!({"id": "core::@1", "name": "core", "type": "STATIC_LIBRARY"})), + ("weird.json", json!({"id": "w", "name": "w", "type": "SOMETHING_NEW"})), + ], + ); + let reply = read(build.path()).unwrap(); + let model = reply.codemodel().unwrap(); + assert_eq!(model.source.as_deref(), Some(Path::new("/src"))); + let targets = &model.configurations[0].targets; + // The escaping reference and the unknown target type are dropped. + assert_eq!(targets.iter().map(|t| t.name.as_str()).collect::>(), ["app", "core"]); + assert_eq!(targets[0].kind, TargetKind::Executable); + assert_eq!(targets[0].dependencies, ["core::@1"]); + assert_eq!(targets[0].compile_groups[0].includes, [PathBuf::from("/src/include")]); + assert_eq!(targets[0].compile_groups[0].defines, ["QT_CORE_LIB"]); + assert!(targets[1].kind.is_buildable_library()); + assert_eq!(reply.cache()["Qt6_DIR"], "C:/Qt/6.8.0/msvc2022_64/lib/cmake/Qt6"); + assert_eq!(reply.toolchains()[0].id.as_deref(), Some("GNU")); + assert_eq!(reply.cmake_files(), ["CMakeLists.txt", "cmake/deps.cmake"]); + } + + #[test] + fn missing_or_partial_replies_are_empty() { + let build = tempfile::tempdir().unwrap(); + assert!(read(build.path()).is_none()); + write_reply(build.path(), &[], &[]); + let reply = read(build.path()).unwrap(); + assert!(reply.codemodel().is_none()); + assert!(reply.cache().is_empty()); + assert!(reply.toolchains().is_empty()); + assert!(reply.cmake_files().is_empty()); + } + + #[test] + fn queries_cover_every_object_read() { + let build = tempfile::tempdir().unwrap(); + write_queries(build.path()).unwrap(); + for name in QUERIES { + assert!(build.path().join(".cmake/api/v1/query/client-openidea").join(name).is_file(), "{name}"); + } + } +} diff --git a/crates/ide-run/src/detect/cmake/mod.rs b/crates/ide-run/src/detect/cmake/mod.rs new file mode 100644 index 000000000..00f3cf583 --- /dev/null +++ b/crates/ide-run/src/detect/cmake/mod.rs @@ -0,0 +1,681 @@ +//! CMake targets come from the File API codemodel, including evaluated subdirectories. + +pub mod cache; +pub mod file_api; +pub mod presets; +pub mod toolchain; + +use super::{ConfigExt, config}; +use crate::{BeforeLaunchTask, RunConfig}; +use file_api::TargetKind; +use ide_core::build_jobs::append_default_jobs; +use ide_core::settings::CMakeProfile; +use std::fs; +use std::path::Path; + +fn before(config: &mut RunConfig, id: &str) { + config.extras.before_launch.push(BeforeLaunchTask { + kind: "build".into(), + target: id.into(), + ..Default::default() + }); +} + +/// Param set on a configure configuration whose build directory has no File API codemodel yet: +/// the targets (and their run configurations) only show up once it has run, so the IDE runs it +/// by itself, as CLion reloads the CMake project. +pub const NEEDS_CONFIGURE: &str = "cmakeNeedsConfigure"; + +/// `build` must be configured before building: not configured at all, or configured without the +/// File API queries (by another tool, or before they were written), so the targets are unknown. +/// `cmake --build` regenerates a configured directory by itself, but never answers new queries. +fn needs_configure(build: &Path) -> bool { + !build.join("CMakeCache.txt").is_file() || file_api::read(build).and_then(|r| r.codemodel()).is_none() +} + +#[derive(Default)] +struct Names { + contexts: Vec<(String, String)>, +} + +impl Names { + fn push(&mut self, out: &mut Vec, config: RunConfig, dir: &str, profile: &str) { + self.contexts.push((dir.replace('\\', "/"), profile.into())); + out.push(config); + } + + fn apply(self, configs: &mut [RunConfig]) { + let names: Vec<_> = configs.iter().map(|c| c.name.clone()).collect(); + for (index, config) in configs.iter_mut().enumerate() { + let duplicates: Vec<_> = names.iter().enumerate().filter(|(_, name)| **name == names[index]).collect(); + if duplicates.len() < 2 { + continue; + } + let (dir, profile) = &self.contexts[index]; + let needs_dir = duplicates.iter().any(|(other, _)| *other != index && self.contexts[*other].1 == *profile); + let mut context = Vec::new(); + if !profile.is_empty() { + context.push(profile.clone()); + } + if needs_dir { + context.push(format!("{}/", dir.trim_end_matches('/'))); + } + if !context.is_empty() { + config.name = format!("{} [{}]", config.name, context.join(" · ")); + } + } + } +} + +pub(super) fn detect(root: &Path, profiles: Option<&[CMakeProfile]>, out: &mut Vec) { + let start = out.len(); + let mut names = Names::default(); + detect_configs(root, profiles, out, &mut names); + names.apply(&mut out[start..]); +} + +fn detect_configs(root: &Path, profiles: Option<&[CMakeProfile]>, out: &mut Vec, names: &mut Names) { + if !root.join("CMakeLists.txt").is_file() { + return; + } + if let Some(profiles) = profiles { + // As in CLion, only the active profile (the first: see `presets::profiles`) builds and + // runs; its configurations keep the same ids whichever profile is active, so their + // customizations survive switching. + if let Some(profile) = profiles.first() { + detect_profile(root, profile, out, names); + } + return; + } + let mut builds = Vec::new(); + if let Ok(entries) = fs::read_dir(root) { + builds.extend(entries.flatten().filter_map(|e| { + let p = e.path(); + (p.is_dir() && p.join("CMakeCache.txt").is_file()).then_some(p) + })); + } + if builds.is_empty() { + builds.push(root.join("build")); + } + builds.sort(); + builds.dedup(); + for build in builds { + let dir = build.strip_prefix(root).unwrap_or(&build).to_string_lossy().replace('\\', "/"); + let configuration = fs::read_to_string(build.join("CMakeCache.txt")) + .ok() + .and_then(|cache| { + let values = cache.lines().find_map(|line| line.strip_prefix("CMAKE_CONFIGURATION_TYPES:STRING="))?; + Some(if values.split(';').any(|c| c == "Debug") { + "Debug".to_owned() + } else { + values.split(';').find(|s| !s.is_empty())?.to_owned() + }) + }) + .unwrap_or_else(|| "Debug".into()); + let prefix = format!("cmake:{dir}"); + let configure_id = format!("{prefix}:configure"); + let build_id = format!("{prefix}:build"); + let mut args = vec!["-S", ".", "-B", &dir, "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"]; + if !build.join("CMakeCache.txt").is_file() { + args.push("-DCMAKE_BUILD_TYPE=Debug"); + } + let mut configure = config(&configure_id, "CMake Configure", "cmake", "cmake", &args); + configure.extras.params.insert("buildDir".into(), dir.clone()); + let configured = !needs_configure(&build); + if !configured { + configure.extras.params.insert(NEEDS_CONFIGURE.into(), "true".into()); + } + names.push(out, configure, &dir, ""); + let mut all = + config(&build_id, "CMake Build", "cmake", "cmake", &["--build", &dir, "--config", &configuration]); + append_default_jobs(&mut all.args); + if !configured { + before(&mut all, &configure_id); + } + names.push(out, all, &dir, ""); + let mut test = config( + format!("{prefix}:test"), + "CTest", + "cmake", + "ctest", + &["--test-dir", &dir, "-C", &configuration, "--output-on-failure"], + ); + before(&mut test, &build_id); + names.push(out, test, &dir, ""); + targets(root, &build, &dir, &prefix, None, out, names); + } +} + +/// Configurations of the active profile; ids start with [`ACTIVE`]. +fn detect_profile(root: &Path, profile: &CMakeProfile, out: &mut Vec, names: &mut Names) { + let dir = if profile.build_dir.trim().is_empty() { + default_build_dir(&profile.build_type) + } else { + profile.build_dir.clone() + }; + let build = root.join(&dir); + let preset = profile.preset.as_ref(); + let prefix = ACTIVE; + let configure_id = format!("{prefix}:configure"); + let build_id = format!("{prefix}:build"); + let start = out.len(); + let mut configure = match preset { + // The preset sets the generator and cache variables; only the compilation database is forced. + Some(preset) => config(&configure_id, "CMake Configure", "cmake", "cmake", &["--preset", &preset.configure]), + None => { + let mut configure = config(&configure_id, "CMake Configure", "cmake", "cmake", &["-S", ".", "-B", &dir]); + if !profile.generator.trim().is_empty() { + configure.args.extend(["-G".into(), profile.generator.clone()]); + } + configure.args.push(format!("-DCMAKE_BUILD_TYPE={}", profile.build_type)); + configure + } + }; + configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into()); + configure.args.extend_from_slice(&profile.cmake_args); + configure.extras.params.insert("buildDir".into(), dir.clone()); + let configured = !needs_configure(&build); + if !configured { + configure.extras.params.insert(NEEDS_CONFIGURE.into(), "true".into()); + } + names.push(out, configure, &dir, &profile.name); + let mut all = config(&build_id, "CMake Build", "cmake", "cmake", &[]); + all.args = build_head(Some(profile), &dir); + if preset.and_then(|p| p.build.as_ref()).is_none() && !profile.build_type.is_empty() { + all.args.extend(["--config".into(), profile.build_type.clone()]); + } + all.args.extend_from_slice(&profile.build_args); + append_default_jobs(&mut all.args); + if !configured { + before(&mut all, &configure_id); + } + names.push(out, all, &dir, &profile.name); + let mut test = match preset.and_then(|p| p.test.as_deref()) { + Some(test) => config(format!("{prefix}:test"), "CTest", "cmake", "ctest", &["--preset", test]), + None => { + let mut test = config(format!("{prefix}:test"), "CTest", "cmake", "ctest", &["--test-dir", &dir]); + if !profile.build_type.is_empty() { + test.args.extend(["-C".into(), profile.build_type.clone()]); + } + test + } + }; + test.args.push("--output-on-failure".into()); + before(&mut test, &build_id); + names.push(out, test, &dir, &profile.name); + targets(root, &build, &dir, prefix, Some(profile), out, names); + for config in &mut out[start..] { + config.env = profile.env.clone(); + config.extras.params.insert("cmakeProfile".into(), profile.name.clone()); + // The toolchain's own cmake (and the ctest next to it). + if let Some(cmake) = &profile.cmake_program { + match config.command.as_str() { + "cmake" => config.command = cmake.to_string_lossy().into_owned(), + "ctest" => config.command = toolchain::ctest_next_to(cmake).to_string_lossy().into_owned(), + _ => {} + } + } + if let (Some(debugger), "cmake-application") = (&profile.debugger, config.kind.as_str()) { + config.extras.params.insert("debugger".into(), debugger.to_string_lossy().into_owned()); + } + } +} + +/// Id prefix of the active profile's configurations. +pub const ACTIVE: &str = "cmake:profile"; + +/// Before only the active profile was detected, every saved profile had configurations, their +/// ids prefixed by `cmake:profile::`. The prefix the active +/// profile had then, `None` when it is a preset (presets came later). +pub fn legacy_prefix(root: &Path, settings: &ide_core::settings::CMakeSettings) -> Option { + let active = presets::profiles(root, settings, &[])?.into_iter().next()?; + if active.preset.is_some() { + return None; + } + let index = settings.profiles.as_ref()?.iter().position(|p| p.name == active.name)?; + Some(format!("{ACTIVE}:{index}:")) +} + +/// `id` under the active profile's current prefix when it has the `legacy` one. +pub fn upgrade_id(id: &str, legacy: &str) -> Option { + let rest = id.strip_prefix(legacy)?; + if matches!(rest, "configure" | "build" | "test") { + return Some(format!("{ACTIVE}:{rest}")); + } + let (_, target) = rest.split_once(':')?; + Some(format!("{ACTIVE}:target:{target}")) +} + +/// Refreshes the launch details generated from the active profile when a saved edit wins. +pub(crate) fn refresh_saved(saved: &mut RunConfig, detected: &RunConfig) { + let switched = saved.extras.params.get("cmakeProfile") != detected.extras.params.get("cmakeProfile"); + saved.command.clone_from(&detected.command); + if detected.kind == "cmake" && switched { + saved.args.clone_from(&detected.args); + } + for key in [ + "buildDir", + "cmakeProfile", + NEEDS_CONFIGURE, + "cmakeTargetKind", + "cmakeSources", + "cmakeSourceRoot", + "cmakeCanonicalSourceRoot", + "debugger", + ] { + if let Some(value) = detected.extras.params.get(key) { + saved.extras.params.insert(key.into(), value.clone()); + } else { + saved.extras.params.remove(key); + } + } +} + +/// A profile's build directory when it names none, as CLion: `cmake-build-debug`, or +/// `cmake-build-default` for the "Default" (empty) build type. +pub fn default_build_dir(build_type: &str) -> String { + let build_type = if build_type.is_empty() { "default".to_owned() } else { build_type.to_lowercase() }; + format!("cmake-build-{build_type}") +} + +/// `cmake --build` with the profile's build preset, else with its directory. +fn build_head(profile: Option<&CMakeProfile>, dir: &str) -> Vec { + match profile.and_then(|p| p.preset.as_ref()).and_then(|p| p.build.as_deref()) { + Some(build) => vec!["--build".into(), "--preset".into(), build.into()], + None => vec!["--build".into(), dir.into()], + } +} + +/// Configure configurations start with `-S` (options) or `--preset`. +fn is_configure(config: &RunConfig) -> bool { + config.kind == "cmake" && config.args.first().is_some_and(|a| a == "-S" || a == "--preset") +} + +fn targets( + root: &Path, + build: &Path, + dir: &str, + prefix: &str, + profile: Option<&CMakeProfile>, + out: &mut Vec, + names: &mut Names, +) { + let Some(model) = file_api::read(build).and_then(|reply| reply.codemodel()) else { return }; + let source_root = model.source.clone().unwrap_or_else(|| root.into()); + if source_root.canonicalize().ok() != root.canonicalize().ok() { + return; + } + let canonical_root = dunce::canonicalize(&source_root).unwrap_or(source_root); + for (index, configuration) in model.configurations.iter().enumerate() { + let name = configuration.name.as_str(); + // The profile's configuration; with CLion's "Default" build type (empty), the first one. + let wanted = |p: &CMakeProfile| { + if p.build_type.is_empty() { index == 0 } else { name.is_empty() || name == p.build_type } + }; + if profile.is_some_and(|p| !wanted(p)) { + continue; + } + let label = profile.map_or(name, |p| p.name.as_str()); + for target in &configuration.targets { + let runnable = target.kind == TargetKind::Executable; + if target.generator_provided || !(runnable || target.kind.is_buildable_library()) { + continue; + } + // One configuration per target for the active profile; automatic discovery can see + // several configurations of a multi-config build directory. + let id = match profile { + Some(_) => format!("{prefix}:target:{}", target.name), + None => format!("{prefix}:{name}:{}", target.name), + }; + let target_build_id = format!("{id}:build"); + let mut build_config = config(&target_build_id, format!("Build {}", target.name), "cmake", "cmake", &[]); + build_config.args = build_head(profile, dir); + build_config.args.extend(["--target".into(), target.name.clone()]); + if !name.is_empty() { + build_config.args.extend(["--config".into(), name.into()]); + } + build_config.extras.params.insert("cmakeTargetKind".into(), target.kind.as_str().into()); + if let Some(profile) = profile { + if name.is_empty() && !profile.build_type.is_empty() { + build_config.args.extend(["--config".into(), profile.build_type.clone()]); + } + build_config.args.extend_from_slice(&profile.build_args); + if !build.join("CMakeCache.txt").is_file() { + before(&mut build_config, &format!("{prefix}:configure")); + } + } + append_default_jobs(&mut build_config.args); + names.push(out, build_config, dir, label); + let (true, Some(artifact)) = (runnable, target.artifacts.first()) else { continue }; + let binary = build.join(artifact); + let mut run = + config(&id, &target.name, "cmake-application", &binary.to_string_lossy(), &[]).debug("lldb-dap"); + before(&mut run, &target_build_id); + let sources: Vec = + target.sources.iter().map(|s| canonical_root.join(s).to_string_lossy().replace('\\', "/")).collect(); + run.extras.params.insert("cmakeSources".into(), sources.join("\n")); + if let Some(recorded) = &model.source { + run.extras.params.insert("cmakeSourceRoot".into(), recorded.to_string_lossy().into_owned()); + run.extras + .params + .insert("cmakeCanonicalSourceRoot".into(), canonical_root.to_string_lossy().replace('\\', "/")); + } + names.push(out, run, dir, label); + } + } +} + +/// Ordered configure/build commands for a CMake build configuration. Executables and CTest +/// are never executed by Build; only their explicit build prerequisites are accepted. +pub fn build_configs(configs: &[RunConfig], id: &str) -> crate::IdeResult> { + fn visit( + configs: &[RunConfig], + id: &str, + chain: &mut Vec, + out: &mut Vec, + ) -> crate::IdeResult<()> { + if chain.iter().any(|entry| entry == id) { + return Err(ide_core::IdeError::invalid("The before launch tasks run in a cycle")); + } + let config = configs + .iter() + .find(|c| c.id == id) + .ok_or_else(|| ide_core::IdeError::not_found(format!("Configuration '{id}' no longer exists")))?; + if !is_configure(config) && !(config.kind == "cmake" && config.args.first().is_some_and(|a| a == "--build")) { + return Err(ide_core::IdeError::invalid("Not a CMake configure or build configuration")); + } + chain.push(id.into()); + for task in &config.extras.before_launch { + if !matches!(task.kind.as_str(), "run" | "build") || task.target.is_empty() { + return Err(ide_core::IdeError::invalid("CMake builds require configure/build prerequisites")); + } + visit(configs, &task.target, chain, out)?; + } + chain.pop(); + if !out.iter().any(|c| c.id == id) { + out.push(config.clone()); + } + Ok(()) + } + let mut out = Vec::new(); + visit(configs, id, &mut Vec::new(), &mut out)?; + Ok(out) +} + +/// Request the File API objects (see [`file_api::QUERIES`]) when executing a configure configuration. +pub fn prepare(config: &RunConfig, cwd: &Path) -> crate::IdeResult<()> { + if is_configure(config) + && let Some(dir) = config.extras.params.get("buildDir") + { + let build = cwd.join(dir); + let generator = config.args.windows(2).find(|a| a[0] == "-G").map(|a| a[1].as_str()); + if let Some(generator) = generator + && let Ok(cache) = fs::read_to_string(build.join("CMakeCache.txt")) + && let Some(cached) = cache.lines().find_map(|l| l.strip_prefix("CMAKE_GENERATOR:INTERNAL=")) + && cached != generator + { + fs::remove_file(build.join("CMakeCache.txt"))?; + let files = build.join("CMakeFiles"); + if files.is_dir() { + fs::remove_dir_all(files)?; + } + } + file_api::write_queries(&build)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::Value; + + #[test] + fn profiles_select_file_api_configuration_and_apply_target_options() { + let root = tempfile::tempdir().unwrap(); + fs::write(root.path().join("CMakeLists.txt"), "project(app)").unwrap(); + let reply = root.path().join("output/.cmake/api/v1/reply"); + fs::create_dir_all(&reply).unwrap(); + let write = |name: &str, value: Value| fs::write(reply.join(name), value.to_string()).unwrap(); + write( + "index-1.json", + serde_json::json!({"objects":[{"kind":"codemodel","version":{"major":2},"jsonFile":"model.json"}]}), + ); + write( + "model.json", + serde_json::json!({"paths":{"source":root.path()},"configurations":[ + {"name":"Debug","targets":[{"jsonFile":"debug.json"}]}, + {"name":"Release","targets":[{"jsonFile":"release.json"}]} + ]}), + ); + for name in ["debug", "release"] { + write( + &format!("{name}.json"), + serde_json::json!({"name":"app","type":"EXECUTABLE","artifacts":[{"path":format!("{name}/app")}]}), + ); + } + let profile = CMakeProfile { + name: "Production".into(), + build_type: "Release".into(), + build_dir: "output".into(), + build_args: ["-j", "8", "--", "verbose=1"].map(String::from).into(), + env: [("FOO".into(), "bar".into())].into(), + ..Default::default() + }; + let mut configs = Vec::new(); + detect(root.path(), Some(std::slice::from_ref(&profile)), &mut configs); + let run = configs.iter().find(|c| c.kind == "cmake-application").unwrap(); + assert!(run.command.ends_with("release/app")); + assert_eq!(run.env, profile.env); + assert_eq!(configs.iter().filter(|c| c.kind == "cmake-application").count(), 1); + let build = configs.iter().find(|c| c.id == run.extras.before_launch[0].target).unwrap(); + assert_eq!( + build.args, + ["--build", "output", "--target", "app", "--config", "Release", "-j", "8", "--", "verbose=1"] + ); + assert_eq!(build.env, profile.env); + assert_eq!(build.extras.before_launch[0].target, "cmake:profile:configure"); + fs::write(root.path().join("output/CMakeCache.txt"), "CMAKE_GENERATOR:INTERNAL=Ninja\n").unwrap(); + let mut configured = Vec::new(); + detect(root.path(), Some(std::slice::from_ref(&profile)), &mut configured); + for id in ["cmake:profile:build", build.id.as_str()] { + let build = configured.iter().find(|c| c.id == id).unwrap(); + assert!(build.extras.before_launch.is_empty(), "{id} should use CMake's automatic regeneration"); + } + let configure = |configs: &[RunConfig]| configs.iter().find(|c| c.id == "cmake:profile:configure").cloned(); + assert!(!configure(&configured).unwrap().extras.params.contains_key(NEEDS_CONFIGURE)); + // Configured by another tool, without the File API queries: configure again to learn the targets. + fs::remove_dir_all(root.path().join("output/.cmake")).unwrap(); + let mut unknown = Vec::new(); + detect(root.path(), Some(std::slice::from_ref(&profile)), &mut unknown); + assert_eq!(configure(&unknown).unwrap().extras.params[NEEDS_CONFIGURE], "true"); + let all = unknown.iter().find(|c| c.id == "cmake:profile:build").unwrap(); + assert_eq!(all.extras.before_launch[0].target, "cmake:profile:configure"); + } + + #[test] + fn build_dependencies_are_scoped_and_reject_cycles_or_executables() { + let root = tempfile::tempdir().unwrap(); + let nested = root.path().join("nested"); + fs::create_dir_all(&nested).unwrap(); + fs::write(nested.join("CMakeLists.txt"), "project(app)").unwrap(); + let configs = crate::detect(root.path()); + let build = configs.iter().find(|c| c.args.first().is_some_and(|a| a == "--build")).unwrap(); + assert_eq!(build.extras.before_launch[0].kind, "build"); + let ordered = build_configs(&configs, &build.id).unwrap(); + assert_eq!(ordered.len(), 2); + assert_eq!(ordered[0].args[0], "-S"); + assert_eq!(ordered[1].args[0], "--build"); + assert_eq!(ordered[1].cwd, build.cwd); + assert!(build_configs(&configs, "missing").is_err()); + let mut cycle = configs.clone(); + let configure = cycle.iter_mut().find(|c| c.id == ordered[0].id).unwrap(); + before(configure, &build.id); + assert!(build_configs(&cycle, &build.id).is_err()); + for kind in ["native", "cmake-application", "shell"] { + let mut invalid = build.clone(); + invalid.kind = kind.into(); + assert!(build_configs(&[invalid.clone()], &invalid.id).is_err()); + } + let test = configs.iter().find(|c| c.command == "ctest").unwrap(); + assert!(build_configs(&configs, &test.id).is_err()); + } + + #[test] + fn generator_change_clears_only_cmake_state_at_launch() { + let root = tempfile::tempdir().unwrap(); + let build = root.path().join("cmake-build-debug"); + fs::create_dir_all(build.join("CMakeFiles")).unwrap(); + fs::write(build.join("CMakeCache.txt"), "CMAKE_GENERATOR:INTERNAL=Unix Makefiles\n").unwrap(); + fs::write(build.join("keep.txt"), "artifact").unwrap(); + fs::write(root.path().join("CMakeLists.txt"), "project(app)").unwrap(); + let mut configs = Vec::new(); + detect(root.path(), Some(&[CMakeProfile { generator: "Ninja".into(), ..Default::default() }]), &mut configs); + assert!(build.join("CMakeCache.txt").exists()); + prepare(&configs[0], root.path()).unwrap(); + assert!(!build.join("CMakeCache.txt").exists()); + assert!(!build.join("CMakeFiles").exists()); + assert!(build.join("keep.txt").exists()); + for query in file_api::QUERIES { + assert!(build.join(".cmake/api/v1/query/client-openidea").join(query).exists(), "{query}"); + } + } + + #[test] + fn preset_profiles_configure_build_and_test_with_their_presets() { + let root = tempfile::tempdir().unwrap(); + fs::write(root.path().join("CMakeLists.txt"), "project(app)").unwrap(); + fs::write( + root.path().join("CMakePresets.json"), + serde_json::json!({"version": 6, "configurePresets": [ + {"name": "dev", "binaryDir": "${sourceDir}/out/dev", "cacheVariables": {"CMAKE_BUILD_TYPE": "Debug"}}, + {"name": "bare", "binaryDir": "out/bare"}], + "buildPresets": [{"name": "dev-build", "configurePreset": "dev"}], + "testPresets": [{"name": "dev-test", "configurePreset": "dev"}]}) + .to_string(), + ) + .unwrap(); + file_api::tests::write_reply( + &root.path().join("out/dev"), + &[( + "codemodel", + 2, + "model.json", + serde_json::json!({"paths": {"source": root.path()}, "configurations": [ + {"name": "Debug", "targets": [{"jsonFile": "app.json"}]}]}), + )], + &[( + "app.json", + serde_json::json!({"id": "app", "name": "app", "type": "EXECUTABLE", "artifacts": [{"path": "app"}]}), + )], + ); + let mut settings = ide_core::settings::CMakeSettings { + enabled_presets: vec!["dev".into(), "bare".into()], + ..Default::default() + }; + let detect_active = |settings: &ide_core::settings::CMakeSettings, toolchains: &[_]| { + let profiles = presets::profiles(root.path(), settings, toolchains).unwrap(); + let mut configs = Vec::new(); + detect(root.path(), Some(&profiles), &mut configs); + configs + }; + let configs = detect_active(&settings, &[]); + let find = |configs: &[RunConfig], id: &str| -> RunConfig { + configs.iter().find(|c| c.id == id).unwrap_or_else(|| panic!("{id}")).clone() + }; + let args = |id: &str| find(&configs, id).args; + assert_eq!(args("cmake:profile:configure"), ["--preset", "dev", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"]); + assert_eq!(args("cmake:profile:build")[..3], ["--build", "--preset", "dev-build"]); + assert_eq!(args("cmake:profile:test"), ["--preset", "dev-test", "--output-on-failure"]); + assert_eq!( + args("cmake:profile:target:app:build")[..5], + ["--build", "--preset", "dev-build", "--target", "app"] + ); + assert_eq!(find(&configs, "cmake:profile:target:app").extras.params["cmakeProfile"], "dev"); + // Only the active profile: no configuration of `bare` until it is switched to. + assert!(configs.iter().all(|c| c.extras.params.get("cmakeProfile").is_some_and(|p| p == "dev"))); + let run = configs.iter().find(|c| c.kind == "cmake-application").unwrap(); + assert!(run.command.replace('\\', "/").ends_with("out/dev/app")); + // Building a target still goes through the preset's configure first. + let ordered = build_configs(&configs, "cmake:profile:build").unwrap(); + assert_eq!(ordered[0].args[0], "--preset"); + settings.active_profile = "bare".into(); + let toolchain = ide_core::settings::Toolchain { + name: "Mine".into(), + cmake: "/opt/cmake/bin/cmake".into(), + debugger: "/opt/gdb".into(), + ..Default::default() + }; + let bare = detect_active(&settings, std::slice::from_ref(&toolchain)); + // The same ids for the other profile, so customizations follow the switch. + assert_eq!(find(&bare, "cmake:profile:build").args[..4], ["--build", "out/bare", "--config", "Debug"]); + assert_eq!(find(&bare, "cmake:profile:test").args[..2], ["--test-dir", "out/bare"]); + // The toolchain's cmake, and the ctest next to it. + assert_eq!(find(&bare, "cmake:profile:configure").command, "/opt/cmake/bin/cmake"); + let ctest = std::path::PathBuf::from(find(&bare, "cmake:profile:test").command); + assert_eq!(ctest, toolchain::ctest_next_to(std::path::Path::new("/opt/cmake/bin/cmake"))); + prepare(&ordered[0], root.path()).unwrap(); + assert!(root.path().join("out/dev/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file()); + } + + #[test] + fn the_default_build_type_passes_no_configuration() { + let root = tempfile::tempdir().unwrap(); + fs::write(root.path().join("CMakeLists.txt"), "project(app)").unwrap(); + let profile = CMakeProfile { build_type: String::new(), ..Default::default() }; + let mut configs = Vec::new(); + detect(root.path(), Some(std::slice::from_ref(&profile)), &mut configs); + let args = |id: &str| configs.iter().find(|c| c.id == id).unwrap().args.clone(); + assert!(args("cmake:profile:configure").contains(&"-DCMAKE_BUILD_TYPE=".to_owned())); + assert_eq!(args("cmake:profile:build")[..2], ["--build", "cmake-build-default"]); + assert!(!args("cmake:profile:build").contains(&"--config".to_owned())); + assert_eq!(args("cmake:profile:test"), ["--test-dir", "cmake-build-default", "--output-on-failure"]); + } + + #[test] + fn libraries_get_build_configs_but_no_run_configs() { + let root = tempfile::tempdir().unwrap(); + fs::write(root.path().join("CMakeLists.txt"), "project(app)").unwrap(); + let build = root.path().join("build"); + fs::create_dir_all(&build).unwrap(); + fs::write(build.join("CMakeCache.txt"), "").unwrap(); + let target = |name: &str, kind: &str| { + ( + format!("{name}.json"), + serde_json::json!({"id": name, "name": name, "type": kind, "artifacts": [{"path": name}]}), + ) + }; + let targets = [ + target("app", "EXECUTABLE"), + target("core", "STATIC_LIBRARY"), + target("plugin", "MODULE_LIBRARY"), + target("headers", "INTERFACE_LIBRARY"), + target("app_autogen", "UTILITY"), + ( + "ZERO_CHECK.json".into(), + serde_json::json!({"id": "z", "name": "ZERO_CHECK", "type": "EXECUTABLE", "isGeneratorProvided": true}), + ), + ]; + let references: Vec<_> = targets.iter().map(|(file, _)| serde_json::json!({ "jsonFile": file })).collect(); + let files: Vec<_> = targets.iter().map(|(file, value)| (file.as_str(), value.clone())).collect(); + file_api::tests::write_reply( + &build, + &[( + "codemodel", + 2, + "model.json", + serde_json::json!({"paths": {"source": root.path()}, "configurations": [{"name": "Debug", "targets": references}]}), + )], + &files, + ); + let mut configs = Vec::new(); + detect(root.path(), None, &mut configs); + let builds: Vec<_> = configs.iter().filter_map(|c| c.name.strip_prefix("Build ")).collect(); + assert_eq!(builds, ["app", "core", "plugin"]); + let runs: Vec<_> = configs.iter().filter(|c| c.kind == "cmake-application").map(|c| c.name.as_str()).collect(); + assert_eq!(runs, ["app"]); + let core = configs.iter().find(|c| c.name == "Build core").unwrap(); + assert_eq!(core.extras.params["cmakeTargetKind"], "STATIC_LIBRARY"); + assert_eq!(build_configs(&configs, &core.id).unwrap().last().unwrap().id, core.id); + } +} diff --git a/crates/ide-run/src/detect/cmake/presets.rs b/crates/ide-run/src/detect/cmake/presets.rs new file mode 100644 index 000000000..28fc3c31e --- /dev/null +++ b/crates/ide-run/src/detect/cmake/presets.rs @@ -0,0 +1,688 @@ +//! `CMakePresets.json` / `CMakeUserPresets.json` turned into CMake profiles. +//! +//! Each visible configure preset whose condition holds becomes a [`CMakeProfile`] carrying a +//! [`CMakePresetRef`], so run-configuration detection and Build Project handle presets with +//! the profile code they already have: `cmake --preset`, `cmake --build --preset` and +//! `ctest --preset` replace the explicit options, and the File API is read from the preset's +//! binary directory. +//! +//! The IDE resolves only what it needs to place the build (binary directory, build type, +//! environment, which build/test preset goes with which configure preset); CMake itself still +//! evaluates the presets when it runs. + +use super::toolchain; +use ide_core::settings::{CMakePresetRef, CMakeProfile, CMakeSettings, Toolchain}; +use serde_json::{Map, Value}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fs; +use std::path::{Component, Path, PathBuf}; + +const PROJECT: &str = "CMakePresets.json"; +const USER: &str = "CMakeUserPresets.json"; +/// Fields `inherits` never copies. +const NOT_INHERITED: [&str; 5] = ["name", "hidden", "inherits", "description", "displayName"]; +/// Object fields merged key by key, the inheriting preset's entries winning. +const MERGED: [&str; 2] = ["cacheVariables", "environment"]; + +/// Every profile Settings › CMake lists: the explicit ones, then one per usable configure preset +/// of `root`, enabled when `enabled_presets` names it. A broken presets file is logged and lists +/// no preset: detection never fails. +pub fn listed(root: &Path, settings: &CMakeSettings) -> Vec { + let mut out = settings.profiles.clone().unwrap_or_default(); + if !settings.ignore_presets { + match load(root) { + Ok(presets) => out.extend(presets.into_iter().map(|mut p| { + p.enabled = settings.enabled_presets.iter().any(|e| Some(e) == p.preset.as_ref().map(|r| &r.configure)); + p + })), + Err(e) => warn_once(root, e), + } + } + out +} + +/// The profiles build, run and debug use: the enabled ones, the active one first (CLion's +/// switcher; else the first enabled), each with its toolchain applied. `None` keeps the +/// automatic discovery of configured build directories: no saved profile and no enabled preset. +pub fn profiles(root: &Path, settings: &CMakeSettings, toolchains: &[Toolchain]) -> Option> { + let mut enabled: Vec<_> = listed(root, settings).into_iter().filter(|p| p.enabled).collect(); + if settings.profiles.is_none() && enabled.is_empty() { + return None; + } + if let Some(at) = enabled.iter().position(|p| p.name == settings.active_profile) { + let active = enabled.remove(at); + enabled.insert(0, active); + } + for profile in &mut enabled { + if let Some(toolchain) = toolchain::find(toolchains, &profile.toolchain) { + toolchain::apply(profile, toolchain); + } + } + Some(enabled) +} + +/// Detection runs often; a broken presets file is logged when its problem first shows up. +fn warn_once(root: &Path, problem: String) { + static REPORTED: std::sync::Mutex> = std::sync::Mutex::new(BTreeMap::new()); + let mut reported = REPORTED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if reported.get(root) != Some(&problem) { + tracing::warn!(root = %root.display(), "ignoring CMake presets: {problem}"); + reported.insert(root.to_path_buf(), problem); + } +} + +/// One profile per visible configure preset whose condition holds, in file order (the user +/// file's own presets after the project's). Empty without a presets file. +pub fn load(root: &Path) -> Result, String> { + let mut raw = Raw::default(); + let user = root.join(USER); + if user.is_file() { + // The user file implicitly includes the project file. + let implicit = root.join(PROJECT).is_file().then(|| root.join(PROJECT)); + collect(root, &user, &mut raw, &mut HashSet::new(), implicit)?; + } else if root.join(PROJECT).is_file() { + collect(root, &root.join(PROJECT), &mut raw, &mut HashSet::new(), None)?; + } else { + return Ok(Vec::new()); + } + let configure = Resolver::new(&raw.configure)?; + let build = Resolver::new(&raw.build)?; + let test = Resolver::new(&raw.test)?; + let mut profiles = Vec::new(); + for name in &configure.order { + let preset = configure.resolve(name)?; + if preset.hidden { + continue; + } + let generator = preset.value["generator"].as_str().map(String::from); + let context = Context::new(root, name, generator.as_deref(), &preset); + if !condition(&preset.value["condition"], &context) { + continue; + } + let mut cmake_args = Vec::new(); + let build_dir = match preset.value["binaryDir"].as_str() { + Some(dir) => relative(root, &context.expand(dir)), + None => { + // Without `binaryDir` (allowed from version 3), the build directory is ours to give. + let dir = format!("build/{name}"); + cmake_args.extend(["-B".to_owned(), dir.clone()]); + dir + } + }; + let companion = |resolver: &Resolver| -> Result, String> { + for other in &resolver.order { + let candidate = resolver.resolve(other)?; + let context = Context::new(root, other, generator.as_deref(), &candidate); + if !candidate.hidden + && candidate.value["configurePreset"] == name.as_str() + && condition(&candidate.value["condition"], &context) + { + return Ok(Some((other.clone(), candidate.value))); + } + } + Ok(None) + }; + let build_preset = companion(&build)?; + // Multi-config generators take the configuration from the build preset; single-config + // ones from CMAKE_BUILD_TYPE. Targets and run configurations follow the same one. + let build_type = match &preset.value["cacheVariables"]["CMAKE_BUILD_TYPE"] { + Value::String(s) => Some(s.clone()), + Value::Object(o) => o.get("value").and_then(Value::as_str).map(String::from), + _ => None, + } + .or_else(|| build_preset.as_ref().and_then(|(_, b)| b["configuration"].as_str().map(String::from))) + .map(|t| context.expand(&t)) + .filter(|t| !t.is_empty()) + .unwrap_or_else(|| "Debug".into()); + let mut build_args = Vec::new(); + // A build preset's own job count wins over the IDE's default one. + if let Some(jobs) = build_preset.as_ref().and_then(|(_, b)| b["jobs"].as_u64()) { + build_args.extend(["-j".to_owned(), jobs.to_string()]); + } + // `null` unsets a variable an inherited preset set. + let cache_variables: Vec = preset.value["cacheVariables"] + .as_object() + .into_iter() + .flatten() + .filter(|(_, value)| !value.is_null()) + .map(|(key, _)| key.clone()) + .collect(); + let toolchain_file = preset.value["toolchainFile"].as_str().is_some_and(|f| !f.trim().is_empty()); + profiles.push(CMakeProfile { + name: name.clone(), + build_type, + // Shown in the settings and kept by a copy; `cmake --preset` sets it by itself. + generator: generator.clone().unwrap_or_default(), + cmake_args, + build_dir, + build_args, + env: context.environment(), + // Listed but disabled until enabled in the settings, as CLion imports presets. + enabled: false, + // CLion's vendor field picks the toolchain of a preset. + toolchain: preset.value["vendor"]["jetbrains.com/clion"]["toolchain"].as_str().unwrap_or_default().into(), + cmake_program: None, + debugger: None, + preset: Some(CMakePresetRef { + configure: name.clone(), + build: build_preset.map(|(name, _)| name), + test: companion(&test)?.map(|(name, _)| name), + cache_variables, + toolchain_file, + }), + }); + } + Ok(profiles) +} + +/// Presets by kind, each with the directory of the file that declared it (`${fileDir}`). +#[derive(Default)] +struct Raw { + configure: Vec<(Value, PathBuf)>, + build: Vec<(Value, PathBuf)>, + test: Vec<(Value, PathBuf)>, +} + +fn collect( + root: &Path, + file: &Path, + raw: &mut Raw, + seen: &mut HashSet, + implicit: Option, +) -> Result<(), String> { + let key = dunce::canonicalize(file).unwrap_or_else(|_| file.to_path_buf()); + if !seen.insert(key) { + // CMake allows a file to be included from several places; its presets count once. + return Ok(()); + } + let text = fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?; + let value: Value = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", file.display()))?; + let dir = file.parent().unwrap_or(Path::new("")).to_path_buf(); + // From version 7, include paths may use the macros that need no preset ($penv, ${sourceDir}…). + let context = Context::for_file(root, &dir); + let includes = value["include"].as_array().into_iter().flatten().filter_map(Value::as_str); + for include in implicit.into_iter().chain(includes.map(|i| dir.join(context.expand(i)))) { + collect(root, &include, raw, seen, None)?; + } + for (field, out) in + [("configurePresets", &mut raw.configure), ("buildPresets", &mut raw.build), ("testPresets", &mut raw.test)] + { + out.extend(value[field].as_array().into_iter().flatten().cloned().map(|p| (p, dir.clone()))); + } + Ok(()) +} + +struct Resolved { + value: Value, + hidden: bool, + file_dir: PathBuf, +} + +struct Resolver<'a> { + by_name: HashMap<&'a str, &'a (Value, PathBuf)>, + order: Vec, +} + +impl<'a> Resolver<'a> { + fn new(presets: &'a [(Value, PathBuf)]) -> Result { + let mut by_name = HashMap::new(); + let mut order = Vec::new(); + for preset in presets { + let name = preset.0["name"].as_str().ok_or("a preset has no name")?; + if by_name.insert(name, preset).is_some() { + return Err(format!("duplicate preset '{name}'")); + } + order.push(name.to_owned()); + } + Ok(Self { by_name, order }) + } + + fn resolve(&self, name: &str) -> Result { + let (own, file_dir) = self.by_name.get(name).ok_or_else(|| format!("unknown preset '{name}'"))?; + Ok(Resolved { + value: self.merged(name, &mut Vec::new())?, + // `hidden` is not inherited, so it is read from the preset itself. + hidden: own["hidden"].as_bool().unwrap_or(false), + file_dir: file_dir.clone(), + }) + } + + /// The preset with every inherited field filled in. Earlier parents win over later ones, + /// and the preset's own fields over all of them. + fn merged(&self, name: &str, stack: &mut Vec) -> Result { + if stack.iter().any(|s| s == name) { + stack.push(name.into()); + return Err(format!("presets inherit in a cycle: {}", stack.join(" -> "))); + } + let (preset, _) = self.by_name.get(name).ok_or_else(|| format!("unknown preset '{name}'"))?; + let mut out: Map = preset.as_object().cloned().unwrap_or_default(); + let parents: Vec = match &preset["inherits"] { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a.iter().filter_map(Value::as_str).map(String::from).collect(), + _ => Vec::new(), + }; + stack.push(name.into()); + for parent in parents { + let parent = self.merged(&parent, stack)?; + for (key, value) in parent.as_object().into_iter().flatten() { + if NOT_INHERITED.contains(&key.as_str()) { + continue; + } + match (out.get_mut(key), value) { + (Some(Value::Object(mine)), Value::Object(theirs)) if MERGED.contains(&key.as_str()) => { + for (k, v) in theirs { + mine.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + (Some(_), _) => {} + (None, _) => { + out.insert(key.clone(), value.clone()); + } + } + } + } + stack.pop(); + Ok(Value::Object(out)) + } +} + +/// What macros expand to for one preset. +struct Context<'a> { + source_dir: String, + preset_name: &'a str, + generator: Option<&'a str>, + file_dir: String, + environment: Map, +} + +impl<'a> Context<'a> { + fn new(root: &Path, preset_name: &'a str, generator: Option<&'a str>, preset: &Resolved) -> Self { + Self { + source_dir: slash(root), + preset_name, + generator, + file_dir: slash(&preset.file_dir), + environment: preset.value["environment"].as_object().cloned().unwrap_or_default(), + } + } + + /// For the paths of `include`: no preset, so `${presetName}`, `${generator}` and `$env{}` + /// (without a preset environment, the IDE's) have nothing preset-specific to expand to. + fn for_file(root: &Path, file_dir: &Path) -> Self { + Self { + source_dir: slash(root), + preset_name: "", + generator: None, + file_dir: slash(file_dir), + environment: Map::new(), + } + } + + fn expand(&self, text: &str) -> String { + self.expand_with(text, &mut Vec::new()) + } + + fn expand_with(&self, text: &str, stack: &mut Vec) -> String { + let mut out = String::new(); + let mut rest = text; + while let Some(at) = rest.find('$') { + out.push_str(&rest[..at]); + let tail = &rest[at..]; + let Some((namespace, name, len)) = macro_at(tail) else { + out.push('$'); + rest = &tail[1..]; + continue; + }; + match namespace { + "" => match name { + "sourceDir" => out.push_str(&self.source_dir), + "sourceParentDir" => { + out.push_str(&slash(Path::new(&self.source_dir).parent().unwrap_or(Path::new("")))) + } + "sourceDirName" => out.push_str( + &Path::new(&self.source_dir).file_name().map(|n| n.to_string_lossy()).unwrap_or_default(), + ), + "presetName" => out.push_str(self.preset_name), + "generator" => out.push_str(self.generator.unwrap_or_default()), + "hostSystemName" => out.push_str(host_system_name()), + "fileDir" => out.push_str(&self.file_dir), + "dollar" => out.push('$'), + "pathListSep" => out.push(if cfg!(windows) { ';' } else { ':' }), + _ => out.push_str(&tail[..len]), + }, + "env" => out.push_str(&self.variable(name, stack).unwrap_or_default()), + "penv" => out.push_str(&std::env::var(name).unwrap_or_default()), + // Vendor macros mean nothing to the IDE. + "vendor" => {} + _ => out.push_str(&tail[..len]), + } + rest = &tail[len..]; + } + out.push_str(rest); + out + } + + /// `$env{name}`: the preset's environment (itself expanded), else the IDE's. + fn variable(&self, name: &str, stack: &mut Vec) -> Option { + match self.environment.get(name) { + Some(Value::Null) => None, + Some(Value::String(value)) if !stack.iter().any(|s| s == name) => { + stack.push(name.into()); + let value = self.expand_with(value, stack); + stack.pop(); + Some(value) + } + // A self-reference falls back to the inherited value, as `PATH=$env{PATH};…` intends. + _ => std::env::var(name).ok(), + } + } + + /// The preset's environment, expanded; `null` entries (unset) are left out. + fn environment(&self) -> BTreeMap { + self.environment.keys().filter_map(|k| Some((k.clone(), self.variable(k, &mut Vec::new())?))).collect() + } +} + +/// `${name}`, `$env{name}`… at the start of `text`: (namespace, name, length). +fn macro_at(text: &str) -> Option<(&str, &str, usize)> { + let open = text.find('{')?; + let namespace = &text[1..open]; + if !namespace.chars().all(|c| c.is_ascii_alphabetic()) { + return None; + } + let close = open + text[open..].find('}')?; + Some((namespace, &text[open + 1..close], close + 1)) +} + +fn host_system_name() -> &'static str { + match std::env::consts::OS { + "windows" => "Windows", + "macos" => "Darwin", + "linux" => "Linux", + "freebsd" => "FreeBSD", + _ => "", + } +} + +fn slash(path: &Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + +/// `dir` relative to `root` when it is inside it (the form profiles store), else absolute. +fn relative(root: &Path, dir: &str) -> String { + let path = Path::new(dir); + let absolute = if path.is_absolute() { path.to_path_buf() } else { root.join(path) }; + let mut normal = PathBuf::new(); + for component in absolute.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + normal.pop(); + } + other => normal.push(other), + } + } + let normal = dunce::simplified(&normal); + // `${sourceDir}` expands to the root as given, so compare with that first; the canonical + // form only helps when the preset spells the path differently (a symlink such as macOS's + // `/var` -> `/private/var`, or an 8.3 short name on Windows). + if let Ok(inner) = normal.strip_prefix(dunce::simplified(root)) { + return slash(inner); + } + // The build directory may not exist yet: resolve its deepest existing ancestor. + let canonical = |p: &Path| dunce::canonicalize(p).ok(); + canonical(root) + .and_then(|canonical_root| { + let (existing, resolved) = normal.ancestors().find_map(|a| Some((a, canonical(a)?)))?; + let resolved = resolved.join(normal.strip_prefix(existing).ok()?); + Some(slash(resolved.strip_prefix(&canonical_root).ok()?)) + }) + .unwrap_or_else(|| slash(normal)) +} + +fn condition(condition: &Value, context: &Context) -> bool { + let string = |key: &str| condition[key].as_str().map(|s| context.expand(s)).unwrap_or_default(); + let list = |key: &str| -> Vec { + condition[key].as_array().into_iter().flatten().filter_map(Value::as_str).map(|s| context.expand(s)).collect() + }; + let matches = || regex::Regex::new(&string("regex")).is_ok_and(|r| r.is_match(&string("string"))); + let mut nested = condition["conditions"].as_array().into_iter().flatten().map(|c| self::condition(c, context)); + match condition { + Value::Null => true, + Value::Bool(b) => *b, + _ => match condition["type"].as_str().unwrap_or_default() { + "const" => condition["value"].as_bool().unwrap_or(false), + "equals" => string("lhs") == string("rhs"), + "notEquals" => string("lhs") != string("rhs"), + "inList" => list("list").contains(&string("string")), + "notInList" => !list("list").contains(&string("string")), + "matches" => matches(), + "notMatches" => !matches(), + "anyOf" => nested.any(|b| b), + "allOf" => nested.all(|b| b), + "not" => !self::condition(&condition["condition"], context), + // An unknown condition is an error for CMake; the preset is not usable. + _ => false, + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn write(root: &Path, name: &str, value: Value) { + fs::write(root.join(name), value.to_string()).unwrap(); + } + + fn names(profiles: &[CMakeProfile]) -> Vec<&str> { + profiles.iter().map(|p| p.name.as_str()).collect() + } + + #[test] + fn inheritance_macros_conditions_and_companion_presets() { + let root = tempfile::tempdir().unwrap(); + let host = host_system_name(); + write( + root.path(), + PROJECT, + json!({"version": 6, "include": ["more/presets.json"], + "configurePresets": [ + {"name": "base", "hidden": true, "generator": "Ninja", "binaryDir": "${sourceDir}/out/${presetName}", + "cacheVariables": {"CMAKE_BUILD_TYPE": "Debug", "A": "base"}, + "environment": {"FROM_BASE": "1", "SHARED": "base"}}, + {"name": "release", "inherits": "base", "cacheVariables": {"CMAKE_BUILD_TYPE": {"type": "STRING", "value": "Release"}}, + "environment": {"SHARED": "mine-$env{FROM_BASE}", "GONE": null}}, + {"name": "other-host", "inherits": "base", + "condition": {"type": "notEquals", "lhs": "${hostSystemName}", "rhs": host}}, + {"name": "this-host", "inherits": "base", + "condition": {"type": "allOf", "conditions": [ + {"type": "inList", "string": "${hostSystemName}", "list": [host]}, + {"type": "matches", "string": "${generator}", "regex": "^Nin"}, + {"type": "not", "condition": {"type": "const", "value": false}}]}} + ], + "buildPresets": [ + {"name": "build-release", "configurePreset": "release", "jobs": 3}, + {"name": "build-release-2", "configurePreset": "release"} + ], + "testPresets": [{"name": "test-release", "configurePreset": "release"}]}), + ); + fs::create_dir_all(root.path().join("more")).unwrap(); + write( + &root.path().join("more"), + "presets.json", + json!({"version": 6, "configurePresets": [{"name": "included", "binaryDir": "${fileDir}/../build/inc"}]}), + ); + let profiles = load(root.path()).unwrap(); + assert_eq!(names(&profiles), ["included", "release", "this-host"]); + let release = &profiles[1]; + assert_eq!(release.build_dir, "out/release"); + assert_eq!(release.build_type, "Release"); + assert_eq!(release.env["FROM_BASE"], "1"); + assert_eq!(release.env["SHARED"], "mine-1"); + assert!(!release.env.contains_key("GONE")); + assert_eq!(release.build_args, ["-j", "3"]); + let reference = release.preset.as_ref().unwrap(); + assert_eq!(reference.build.as_deref(), Some("build-release")); + assert_eq!(reference.test.as_deref(), Some("test-release")); + assert_eq!(profiles[0].build_dir, "build/inc"); + assert_eq!(profiles[2].build_type, "Debug"); + assert!(profiles[2].preset.as_ref().unwrap().build.is_none()); + } + + #[test] + fn user_presets_include_the_project_file_and_missing_binary_dir_is_given() { + let root = tempfile::tempdir().unwrap(); + write(root.path(), PROJECT, json!({"version": 3, "configurePresets": [{"name": "dev"}]})); + write(root.path(), USER, json!({"version": 3, "configurePresets": [{"name": "mine", "inherits": "dev"}]})); + let profiles = load(root.path()).unwrap(); + assert_eq!(names(&profiles), ["dev", "mine"]); + assert_eq!(profiles[1].build_dir, "build/mine"); + assert_eq!(profiles[1].cmake_args, ["-B", "build/mine"]); + } + + #[test] + fn errors_are_reported_and_ignored_by_profiles() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + PROJECT, + json!({"version": 3, "configurePresets": [ + {"name": "a", "inherits": "b"}, {"name": "b", "inherits": "a"}]}), + ); + assert!(load(root.path()).unwrap_err().contains("cycle")); + let explicit = CMakeProfile::default(); + let settings = CMakeSettings { profiles: Some(vec![explicit.clone()]), ..Default::default() }; + assert_eq!(profiles(root.path(), &settings, &[]), Some(vec![explicit])); + assert_eq!(profiles(root.path(), &CMakeSettings::default(), &[]), None); + write(root.path(), PROJECT, json!({"version": 3, "configurePresets": [{"name": "a"}, {"name": "a"}]})); + assert!(load(root.path()).unwrap_err().contains("duplicate")); + fs::write(root.path().join(PROJECT), "{").unwrap(); + assert!(load(root.path()).is_err()); + } + + #[test] + fn build_preset_configuration_include_macros_and_unresolved_roots() { + let base = tempfile::tempdir().unwrap(); + let root = base.path().join("app"); + fs::create_dir_all(root.join("cmake")).unwrap(); + write( + &root, + PROJECT, + json!({"version": 7, "include": ["${sourceDir}/cmake/more.json"], + "configurePresets": [{"name": "vs", "generator": "Ninja Multi-Config", "binaryDir": "${sourceDir}/out/vs"}], + "buildPresets": [{"name": "vs-release", "configurePreset": "vs", "configuration": "Release"}]}), + ); + write(&root.join("cmake"), "more.json", json!({"version": 7, "configurePresets": [{"name": "extra"}]})); + let profiles = load(&root).unwrap(); + assert_eq!(names(&profiles), ["extra", "vs"]); + // The build preset's configuration, so targets and runs match what CMake Build builds. + assert_eq!(profiles[1].build_type, "Release"); + assert_eq!(profiles[1].build_dir, "out/vs"); + // A root spelled differently from its canonical form (`..`, symlinks, 8.3 names) still + // gives relative build directories, existing or not. + let spelled = base.path().join("app").join("cmake").join(".."); + assert_eq!(relative(&spelled, &slash(&root.join("out/vs"))), "out/vs"); + fs::create_dir_all(root.join("out/vs")).unwrap(); + assert_eq!(relative(&spelled, &slash(&root.join("out/vs"))), "out/vs"); + assert_eq!(relative(&root, "../elsewhere"), slash(&base.path().join("elsewhere"))); + } + + #[test] + fn presets_are_listed_disabled_until_enabled_and_the_active_profile_comes_first() { + let root = tempfile::tempdir().unwrap(); + assert_eq!(profiles(root.path(), &CMakeSettings::default(), &[]), None); + write( + root.path(), + PROJECT, + json!({"version": 3, "configurePresets": [ + {"name": "one", "binaryDir": "b1", "vendor": {"jetbrains.com/clion": {"toolchain": "MinGW"}}}, + {"name": "two", "binaryDir": "b2"}]}), + ); + let mut settings = CMakeSettings::default(); + // Listed, but like CLion's imported presets disabled: automatic discovery stays. + let listed_names = listed(root.path(), &settings); + assert_eq!(names(&listed_names), ["one", "two"]); + assert!(listed_names.iter().all(|p| !p.enabled)); + assert_eq!(listed_names[0].toolchain, "MinGW"); + assert_eq!(profiles(root.path(), &settings, &[]), None); + settings.enabled_presets = vec!["two".into(), "one".into()]; + let explicit = |name: &str, enabled| CMakeProfile { name: name.into(), enabled, ..Default::default() }; + settings.profiles = Some(vec![explicit("Mine", true), explicit("Off", false)]); + assert_eq!(names(&listed(root.path(), &settings)), ["Mine", "Off", "one", "two"]); + assert_eq!(names(&profiles(root.path(), &settings, &[]).unwrap()), ["Mine", "one", "two"]); + settings.active_profile = "two".into(); + assert_eq!(names(&profiles(root.path(), &settings, &[]).unwrap()), ["two", "Mine", "one"]); + // An unknown or disabled active profile leaves the order alone. + settings.active_profile = "Off".into(); + assert_eq!(names(&profiles(root.path(), &settings, &[]).unwrap())[0], "Mine"); + let toolchains = [ + Toolchain { name: "System".into(), ..Default::default() }, + Toolchain { + name: "MinGW".into(), + kind: ide_core::settings::ToolchainKind::MinGw, + path: "/mingw".into(), + ..Default::default() + }, + ]; + let used = profiles(root.path(), &settings, &toolchains).unwrap(); + let one = used.iter().find(|p| p.name == "one").unwrap(); + assert!(one.cmake_args.iter().any(|a| a.starts_with("-DCMAKE_C_COMPILER=")), "{:?}", one.cmake_args); + assert!(used[0].cmake_args.is_empty(), "the default System toolchain adds nothing"); + settings.ignore_presets = true; + assert_eq!(names(&profiles(root.path(), &settings, &[]).unwrap()), ["Mine"]); + // Every saved profile disabled: nothing is built, no fallback to discovery. + settings.profiles = Some(vec![explicit("Off", false)]); + assert_eq!(profiles(root.path(), &settings, &[]), Some(vec![])); + settings.profiles = None; + assert_eq!(profiles(root.path(), &settings, &[]), None); + } + + #[test] + fn a_toolchain_leaves_what_the_preset_sets_alone() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + PROJECT, + json!({"version": 3, "configurePresets": [ + {"name": "base", "hidden": true, "binaryDir": "out/${presetName}", + "cacheVariables": {"CMAKE_C_COMPILER": "clang", "CMAKE_MAKE_PROGRAM": "/opt/make"}}, + {"name": "cache", "inherits": "base", "generator": "MinGW Makefiles", + "cacheVariables": {"CMAKE_MAKE_PROGRAM": null}}, + {"name": "file", "generator": "Unix Makefiles", "binaryDir": "out/file", "toolchainFile": "cross.cmake"}, + {"name": "file-var", "binaryDir": "out/file-var", + "cacheVariables": {"CMAKE_TOOLCHAIN_FILE": "cross.cmake"}}, + {"name": "vs", "generator": "Visual Studio 17 2022", "binaryDir": "out/vs"}, + {"name": "multi", "generator": "Ninja Multi-Config", "binaryDir": "out/multi"}, + {"name": "plain", "binaryDir": "out/plain"}]}), + ); + let settings = CMakeSettings { + enabled_presets: ["cache", "file", "file-var", "vs", "multi", "plain"].map(String::from).to_vec(), + ..Default::default() + }; + let mingw = Toolchain { + name: "MinGW".into(), + kind: ide_core::settings::ToolchainKind::MinGw, + path: "/mingw".into(), + ..Default::default() + }; + let used = profiles(root.path(), &settings, &[mingw]).unwrap(); + let defines = |name: &str| -> Vec { + let profile = used.iter().find(|p| p.name == name).unwrap(); + profile + .cmake_args + .iter() + .filter_map(|a| a.strip_prefix("-D")?.split('=').next().map(String::from)) + .collect() + }; + // Its own compiler stays; the make program it unset again comes from the toolchain. + assert_eq!(defines("cache"), ["CMAKE_CXX_COMPILER", "CMAKE_MAKE_PROGRAM"]); + assert!(defines("file").is_empty()); + assert!(defines("file-var").is_empty()); + // Visual Studio builds with MSBuild, Ninja Multi-Config with Ninja: never mingw32-make. + assert_eq!(defines("vs"), ["CMAKE_C_COMPILER", "CMAKE_CXX_COMPILER"]); + assert_eq!(defines("multi"), ["CMAKE_C_COMPILER", "CMAKE_CXX_COMPILER"]); + assert_eq!(defines("plain"), ["CMAKE_C_COMPILER", "CMAKE_CXX_COMPILER"]); + } +} diff --git a/crates/ide-run/src/detect/cmake/toolchain.rs b/crates/ide-run/src/detect/cmake/toolchain.rs new file mode 100644 index 000000000..4d54b4dbe --- /dev/null +++ b/crates/ide-run/src/detect/cmake/toolchain.rs @@ -0,0 +1,236 @@ +//! Toolchains (Settings › Build, Execution, Deployment › Toolchains) applied to CMake profiles, +//! as CLion does: the toolchain's compilers and build tool become cache variables of the +//! configure step, its `cmake` runs configure, build and CTest, a MinGW `bin` goes first on +//! `PATH`, and its debugger is the one C/C++ launches prefer. + +use ide_core::settings::{CMakeProfile, Toolchain, ToolchainKind}; +use std::path::{Path, PathBuf}; + +/// The toolchain named `name`, else the default one (the first); `None` without toolchains, +/// which keeps everything from `PATH`. +pub fn find<'a>(toolchains: &'a [Toolchain], name: &str) -> Option<&'a Toolchain> { + toolchains.iter().find(|t| !name.is_empty() && t.name == name).or_else(|| toolchains.first()) +} + +fn exe(name: &str) -> String { + if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() } +} + +/// What a toolchain contributes once its empty fields are filled from its kind. +#[derive(Debug, Default, PartialEq)] +pub struct Tools { + pub cmake: Option, + pub c_compiler: Option, + pub cxx_compiler: Option, + pub build_tool: Option, + pub debugger: Option, + /// Put first on `PATH`. + pub path: Option, +} + +pub fn tools(toolchain: &Toolchain) -> Tools { + let given = |field: &str| Some(field.trim()).filter(|f| !f.is_empty()).map(String::from); + let bin = (toolchain.kind == ToolchainKind::MinGw && !toolchain.path.trim().is_empty()) + .then(|| Path::new(toolchain.path.trim()).join("bin")); + let from_bin = |name: &str| bin.as_ref().map(|b| b.join(exe(name)).to_string_lossy().into_owned()); + Tools { + cmake: given(&toolchain.cmake).map(PathBuf::from), + c_compiler: given(&toolchain.c_compiler).or_else(|| from_bin("gcc")), + cxx_compiler: given(&toolchain.cxx_compiler).or_else(|| from_bin("g++")), + build_tool: given(&toolchain.build_tool).or_else(|| from_bin("mingw32-make")), + debugger: given(&toolchain.debugger).or_else(|| from_bin("gdb")).map(PathBuf::from), + path: bin, + } +} + +fn is_ninja(tool: &str) -> bool { + tool_name(tool) == "ninja" || tool_name(tool) == "ninja-build" +} + +fn tool_name(tool: &str) -> String { + let name = tool.rsplit(['/', '\\']).next().unwrap_or_default().to_ascii_lowercase(); + name.strip_suffix(".exe").unwrap_or(&name).to_owned() +} + +/// Whether the chosen generator is known to use this tool. +fn drives(generator: &str, tool: &str) -> bool { + match generator.trim() { + "Ninja" | "Ninja Multi-Config" => is_ninja(tool), + "Unix Makefiles" | "MSYS Makefiles" => matches!(tool_name(tool).as_str(), "make" | "gmake"), + "MinGW Makefiles" => tool_name(tool) == "mingw32-make", + "NMake Makefiles" => tool_name(tool) == "nmake", + "NMake Makefiles JOM" => tool_name(tool) == "jom", + _ => false, + } +} + +/// Folds `toolchain` into `profile`: cache variables the profile does not already set (by its +/// CMake options or its preset), the generator a MinGW build tool needs, `PATH`, and the +/// programs to run. +pub fn apply(profile: &mut CMakeProfile, toolchain: &Toolchain) { + let tools = tools(toolchain); + let explicit_generator = profile.cmake_args.iter().enumerate().rev().find_map(|(index, arg)| { + arg.strip_prefix("-G").map(|value| { + if value.is_empty() { profile.cmake_args.get(index + 1).map_or("", String::as_str) } else { value } + }) + }); + // CMake might choose Visual Studio or NMake on Windows, so name the MinGW generator + // when the profile leaves that choice to the IDE. + if toolchain.kind == ToolchainKind::MinGw + && profile.preset.is_none() + && profile.generator.trim().is_empty() + && explicit_generator.is_none() + { + let ninja = tools.build_tool.as_deref().is_some_and(is_ninja); + profile.generator = if ninja { "Ninja" } else { "MinGW Makefiles" }.into(); + } + let generator = explicit_generator.unwrap_or(&profile.generator); + let preset = profile.preset.as_ref(); + let sets = |name: &str| { + profile.cmake_args.iter().any(|a| { + a.strip_prefix("-D") + .is_some_and(|d| d.starts_with(&format!("{name}=")) || d.starts_with(&format!("{name}:"))) + }) || preset.is_some_and(|p| p.cache_variables.iter().any(|v| v == name)) + }; + // A toolchain file picks the compilers and the build tool. + let toolchain_file = sets("CMAKE_TOOLCHAIN_FILE") || preset.is_some_and(|p| p.toolchain_file); + let fits = |name: &str, value: &str| match name { + "CMAKE_MAKE_PROGRAM" => drives(generator, value), + _ => true, + }; + let defines: Vec = [ + ("CMAKE_C_COMPILER", &tools.c_compiler), + ("CMAKE_CXX_COMPILER", &tools.cxx_compiler), + ("CMAKE_MAKE_PROGRAM", &tools.build_tool), + ] + .into_iter() + .filter(|(name, value)| !toolchain_file && !sets(name) && value.as_deref().is_some_and(|v| fits(name, v))) + .filter_map(|(name, value)| Some(format!("-D{name}={}", value.as_ref()?))) + .collect(); + profile.cmake_args.splice(0..0, defines); + if let Some(dir) = tools.path { + let inherited = profile.env.get("PATH").cloned().or_else(|| std::env::var("PATH").ok()).unwrap_or_default(); + let joined = std::env::join_paths(std::iter::once(dir).chain(std::env::split_paths(&inherited))) + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or(inherited); + profile.env.insert("PATH".into(), joined); + } + profile.cmake_program = tools.cmake; + profile.debugger = tools.debugger; +} + +/// The executables a toolchain check looks up on `PATH` for each field the toolchain leaves +/// empty, in order: what CMake itself would most likely pick. +pub const FALLBACKS: [(&str, &[&str]); 5] = [ + ("cmake", &["cmake"]), + ("buildTool", &["ninja", "make", "mingw32-make"]), + ("cCompiler", &["cc", "gcc", "clang"]), + ("cxxCompiler", &["c++", "g++", "clang++"]), + ("debugger", &["gdb", "lldb-dap"]), +]; + +/// MinGW and MSYS2 installs in their usual places (Windows only): directories holding +/// `bin/gcc.exe`, MSYS2's environments first. +pub fn detect_mingw() -> Vec { + if !cfg!(windows) { + return Vec::new(); + } + let mut candidates: Vec = Vec::new(); + let drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into()); + let root = PathBuf::from(format!("{drive}\\")); + for msys in [root.join("msys64"), root.join("msys2")] { + candidates.extend(["ucrt64", "mingw64", "clang64", "mingw32"].map(|env| msys.join(env))); + } + candidates.extend([root.join("mingw64"), root.join("MinGW"), root.join("mingw32")]); + if let Some(home) = std::env::var_os("USERPROFILE").map(PathBuf::from) { + candidates.push(home.join("scoop").join("apps").join("mingw").join("current")); + } + if let Some(data) = std::env::var_os("ProgramData").map(PathBuf::from) { + candidates + .push(data.join("chocolatey").join("lib").join("mingw").join("tools").join("install").join("mingw64")); + } + for programs in ["ProgramFiles", "ProgramFiles(x86)"].iter().filter_map(std::env::var_os).map(PathBuf::from) { + // mingw-w64 installers: Program Files\mingw-w64\\mingw64 + if let Ok(versions) = std::fs::read_dir(programs.join("mingw-w64")) { + candidates.extend(versions.flatten().map(|v| v.path().join("mingw64"))); + } + } + let mut found: Vec = Vec::new(); + for dir in candidates { + if dir.join("bin").join("gcc.exe").is_file() && !found.contains(&dir) { + found.push(dir); + } + } + found +} + +/// `ctest` next to the toolchain's `cmake`. +pub fn ctest_next_to(cmake: &Path) -> PathBuf { + cmake.with_file_name(exe("ctest")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn mingw() -> Toolchain { + Toolchain { name: "MinGW".into(), kind: ToolchainKind::MinGw, path: "/opt/mingw".into(), ..Default::default() } + } + + #[test] + fn finds_by_name_else_the_default() { + let list = [Toolchain { name: "A".into(), ..Default::default() }, mingw()]; + assert_eq!(find(&list, "MinGW").unwrap().name, "MinGW"); + assert_eq!(find(&list, "").unwrap().name, "A"); + assert_eq!(find(&list, "gone").unwrap().name, "A"); + assert!(find(&[], "A").is_none()); + } + + #[test] + fn mingw_fills_compilers_make_generator_path_and_gdb() { + let mut profile = CMakeProfile { + cmake_args: vec!["-DCMAKE_CXX_COMPILER=clang++".into()], + env: [("PATH".into(), "/usr/bin".into())].into(), + ..Default::default() + }; + apply(&mut profile, &mingw()); + let bin = Path::new("/opt/mingw").join("bin"); + let at = |name: &str| bin.join(exe(name)).to_string_lossy().into_owned(); + assert_eq!( + profile.cmake_args, + [ + format!("-DCMAKE_C_COMPILER={}", at("gcc")), + format!("-DCMAKE_MAKE_PROGRAM={}", at("mingw32-make")), + // The profile's own option wins over the toolchain's. + "-DCMAKE_CXX_COMPILER=clang++".into(), + ] + ); + assert_eq!(profile.generator, "MinGW Makefiles"); + assert_eq!(std::env::split_paths(&profile.env["PATH"]).next(), Some(bin.clone())); + assert_eq!(profile.debugger, Some(bin.join(exe("gdb")))); + assert!(profile.cmake_program.is_none()); + } + + #[test] + fn system_uses_given_paths_and_keeps_presets_and_generators() { + let system = Toolchain { + name: "Custom".into(), + cmake: "/opt/cmake/bin/cmake".into(), + build_tool: "/usr/bin/ninja".into(), + debugger: "/usr/bin/gdb".into(), + ..Default::default() + }; + let mut profile = CMakeProfile { generator: "Ninja".into(), ..Default::default() }; + apply(&mut profile, &system); + assert_eq!(profile.cmake_args, ["-DCMAKE_MAKE_PROGRAM=/usr/bin/ninja"]); + assert_eq!(profile.cmake_program.as_deref(), Some(Path::new("/opt/cmake/bin/cmake"))); + assert!(!profile.env.contains_key("PATH")); + assert_eq!(ctest_next_to(Path::new("/opt/cmake/bin/cmake")), Path::new("/opt/cmake/bin").join(exe("ctest"))); + let mut preset = CMakeProfile { preset: Some(Default::default()), ..Default::default() }; + apply(&mut preset, &mingw()); + assert!(preset.generator.is_empty(), "a preset names its own generator"); + let mut ninja = CMakeProfile::default(); + apply(&mut ninja, &Toolchain { build_tool: "C:/tools/ninja.exe".into(), ..mingw() }); + assert_eq!(ninja.generator, "Ninja"); + } +} diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index eed744095..f7c2f6a0f 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -25,7 +25,10 @@ pub mod wrap; pub mod xcode; pub mod xcode_clean; -pub use detect::cmake::{build_configs as cmake_build_configs, prepare as prepare_cmake}; +pub use detect::cmake::cache as cmake_cache; +pub use detect::cmake::presets::{listed as cmake_listed_profiles, load as cmake_presets, profiles as cmake_profiles}; +pub use detect::cmake::toolchain as cmake_toolchain; +pub use detect::cmake::{build_configs as cmake_build_configs, file_api as cmake_file_api, prepare as prepare_cmake}; pub use process::{DetachedProcessKills, ProcessManager, StartOptions}; use ide_core::{IdeResult, RunId}; @@ -301,6 +304,57 @@ pub fn detect_with_profiles( detect::detect_with_profiles(root, excluded_poms, profiles) } +/// Detects configurations with the CMake settings: their profiles and the presets of the root +/// CMake project, and the presets of nested CMake projects. +pub fn detect_with_cmake( + root: &Path, + excluded_poms: &[PathBuf], + cmake: &ide_core::settings::CMakeSettings, + toolchains: &[ide_core::settings::Toolchain], +) -> Vec { + detect::detect_with_cmake(root, excluded_poms, cmake, toolchains) +} + +/// Saved configurations (and removed ids) of the active CMake profile that still carry the ids +/// it had when every profile was detected (`cmake:profile::…`), renamed to the ids detection +/// gives them now, so their program arguments, environment and before-launch tasks still apply. +pub fn upgrade_cmake_profile_ids( + root: &Path, + cmake: &ide_core::settings::CMakeSettings, + saved: &mut [RunConfig], + suppressed: &mut [String], +) { + let Some(legacy) = detect::cmake::legacy_prefix(root, cmake) else { return }; + let upgrade = |id: &mut String| { + if let Some(new) = detect::cmake::upgrade_id(id, &legacy) { + *id = new; + } + }; + for config in saved { + upgrade(&mut config.id); + config + .extras + .before_launch + .iter_mut() + .filter(|t| matches!(t.kind.as_str(), "run" | "build")) + .for_each(|t| upgrade(&mut t.target)); + config.extras.compound.iter_mut().for_each(upgrade); + } + suppressed.iter_mut().for_each(upgrade); +} + +/// Keeps edits to CMake profile configurations while refreshing their generated launch details. +pub fn refresh_saved_cmake_profiles(saved: &mut [RunConfig], detected: &[RunConfig]) { + for config in saved { + if let Some(fresh) = detected + .iter() + .find(|d| d.id == config.id && d.kind == config.kind && d.extras.params.contains_key("cmakeProfile")) + { + detect::cmake::refresh_saved(config, fresh); + } + } +} + /// Configurations of the Maven / Gradle builds a user linked in `dirs`, at any depth below `root` or outside it. pub fn detect_builds(root: &Path, dirs: &[PathBuf]) -> Vec { detect::detect_builds(root, dirs) diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs index 8160bf3a7..219fc1b98 100644 --- a/crates/ide-run/tests/detect.rs +++ b/crates/ide-run/tests/detect.rs @@ -934,10 +934,17 @@ fn cmake_detection_is_read_only_and_preserves_existing_build_directories() { assert!(!dir.path().join("build").exists()); assert!(!dir.path().join("cmake-build-debug/.cmake").exists()); let build = find(&configs, "cmake:cmake-build-debug:build"); - assert!(build.extras.before_launch.is_empty(), "a configured build regenerates by itself"); + // Configured by another tool, without File API reply: configure again to learn the targets. + assert_eq!(build.extras.before_launch[0].target, configure.id); + assert_eq!(configure.extras.params["cmakeNeedsConfigure"], "true"); assert!(build.args.windows(2).any(|a| a == ["--config", "Release"])); let test = find(&configs, "cmake:cmake-build-debug:test"); assert_eq!(test.extras.before_launch[0].target, build.id); + cmake_reply(dir.path(), "cmake-build-debug", &[("Release", &[])]); + let configs = detect(dir.path()); + let build = find(&configs, "cmake:cmake-build-debug:build"); + assert!(build.extras.before_launch.is_empty(), "a configured build regenerates by itself"); + assert!(!find(&configs, "cmake:cmake-build-debug:configure").extras.params.contains_key("cmakeNeedsConfigure")); } fn cmake_reply(root: &Path, dir: &str, configurations: &[(&str, &[&str])]) { @@ -1030,37 +1037,32 @@ fn cmake_multiconfig_names_use_configuration_without_redundant_directory() { } #[test] -fn cmake_profile_names_disambiguate_before_adding_directory_locations() { +fn only_the_active_cmake_profile_is_detected_under_the_same_ids() { use ide_core::settings::CMakeProfile; let root = project(&[("CMakeLists.txt", "project(demo)")]); - cmake_reply(root.path(), "out/debug", &[("Debug", &["hello"])]); - cmake_reply(root.path(), "out/release", &[("Release", &["hello"])]); - for same_name in [false, true] { - let profiles = [ - CMakeProfile { name: "Development".into(), build_dir: "out/debug".into(), ..Default::default() }, - CMakeProfile { - name: if same_name { "Development" } else { "Production" }.into(), - build_type: "Release".into(), - build_dir: "out/release".into(), - ..Default::default() - }, - ]; + cmake_reply(root.path(), "out/debug", &[("Debug", &["hello", "build", "configure", "test"])]); + cmake_reply(root.path(), "out/release", &[("Release", &["hello", "build", "configure", "test"])]); + let development = CMakeProfile { name: "Development".into(), build_dir: "out/debug".into(), ..Default::default() }; + let production = CMakeProfile { + name: "Production".into(), + build_type: "Release".into(), + build_dir: "out/release".into(), + ..Default::default() + }; + // The active profile comes first (`cmake_profiles` puts it there). + for profiles in [[development.clone(), production.clone()], [production, development]] { let configs = ide_run::detect_with_profiles(root.path(), &[], Some(&profiles)); - for (index, profile) in profiles.iter().enumerate() { - let context = - if same_name { format!("{} · {}/", profile.name, profile.build_dir) } else { profile.name.clone() }; - for (id, name) in [("configure", "CMake Configure"), ("build", "CMake Build"), ("test", "CTest")] { - assert_eq!(find(&configs, &format!("cmake:profile:{index}:{id}")).name, format!("{name} [{context}]")); - } - assert_eq!( - find(&configs, &format!("cmake:profile:{index}:{}:hello", profile.build_type)).name, - format!("hello [{context}]") - ); - assert_eq!( - find(&configs, &format!("cmake:profile:{index}:{}:hello:build", profile.build_type)).name, - format!("Build hello [{context}]") - ); + let active = &profiles[0]; + for (id, name) in [("configure", "CMake Configure"), ("build", "CMake Build"), ("test", "CTest")] { + assert_eq!(find(&configs, &format!("cmake:profile:{id}")).name, name); + assert_eq!(find(&configs, &format!("cmake:profile:target:{id}")).name, id); } + let hello = find(&configs, "cmake:profile:target:hello"); + assert_eq!(hello.name, "hello"); + assert!(hello.command.replace('\\', "/").contains(&active.build_dir), "{}", hello.command); + assert_eq!(hello.extras.params["cmakeProfile"], active.name); + assert_eq!(find(&configs, "cmake:profile:target:hello:build").name, "Build hello"); + assert!(configs.iter().all(|c| c.extras.params["cmakeProfile"] == active.name)); } } @@ -1181,9 +1183,10 @@ fn cmake_profiles_control_commands_names_and_environment() { build_dir: "output dir".into(), build_args: ["-j", "8", "--", "VERBOSE=1"].map(String::from).into(), env: [("MY_ENV".into(), "yes".into())].into(), + ..Default::default() }; let configs = ide_run::detect_with_profiles(dir.path(), &[], Some(std::slice::from_ref(&profile))); - let configure = find(&configs, "cmake:profile:0:configure"); + let configure = find(&configs, "cmake:profile:configure"); let mut expected = vec!["-S", ".", "-B", "output dir"]; if !generator.is_empty() { expected.extend(["-G", generator]); @@ -1198,14 +1201,14 @@ fn cmake_profiles_control_commands_names_and_environment() { ]); assert_eq!(configure.args, expected); assert_eq!(configure.name, "CMake Configure"); - let build = find(&configs, "cmake:profile:0:build"); + let build = find(&configs, "cmake:profile:build"); assert_eq!(build.args, ["--build", "output dir", "--config", "Release", "-j", "8", "--", "VERBOSE=1"]); assert_eq!(build.extras.before_launch[0].target, configure.id); assert!(configs.iter().all(|c| c.env == profile.env)); + // Only the first (active) profile builds. let configs = ide_run::detect_with_profiles(dir.path(), &[], Some(&[CMakeProfile::default(), profile])); - assert!(find(&configs, "cmake:profile:0:build").name.ends_with("[Debug]")); - assert!(find(&configs, "cmake:profile:1:build").name.ends_with("[Production]")); - assert_eq!(find(&configs, "cmake:profile:0:build").args[1], "cmake-build-debug"); + assert_eq!(find(&configs, "cmake:profile:build").args[1], "cmake-build-debug"); + assert!(configs.iter().all(|c| c.extras.params["cmakeProfile"] == "Debug")); } assert_eq!(ide_run::detect_with_profiles(dir.path(), &[], None), detect(dir.path())); assert!(ide_run::detect_with_profiles(dir.path(), &[], Some(&[])).is_empty()); @@ -1220,19 +1223,20 @@ fn cmake_profile_build_configures_only_without_a_cache() { let build_dir = root.path().join(if dir.is_empty() { "cmake-build-debug" } else { dir }); for cached in [false, true] { if cached { - fs::create_dir_all(&build_dir).unwrap(); + let relative = build_dir.strip_prefix(root.path()).unwrap().to_string_lossy().into_owned(); + cmake_reply(root.path(), &relative, &[("Debug", &[])]); // Generator changes are handled by an explicit Configure, not every Build. fs::write(build_dir.join("CMakeCache.txt"), "CMAKE_GENERATOR:INTERNAL=Unix Makefiles\n").unwrap(); } let configs = ide_run::detect_with_profiles(root.path(), &[], Some(std::slice::from_ref(&profile))); - let build = find(&configs, "cmake:profile:0:build"); + let build = find(&configs, "cmake:profile:build"); if cached { assert!(build.extras.before_launch.is_empty()); } else { assert_eq!(build.extras.before_launch.len(), 1); - assert_eq!(build.extras.before_launch[0].target, "cmake:profile:0:configure"); + assert_eq!(build.extras.before_launch[0].target, "cmake:profile:configure"); } - assert_eq!(find(&configs, "cmake:profile:0:test").extras.before_launch[0].target, build.id); + assert_eq!(find(&configs, "cmake:profile:test").extras.before_launch[0].target, build.id); } } } @@ -1545,3 +1549,81 @@ fn csproj_under_unreal_generated_directories_is_not_detected() { let c = detect(dir.path()); assert!(c.is_empty(), "{:?}", ids(&c)); } + +#[test] +fn nested_cmake_projects_use_their_own_presets() { + use ide_core::settings::{CMakeProfile, CMakeSettings}; + let presets = r#"{"version": 3, "configurePresets": [{"name": "dev", "binaryDir": "out/dev"}]}"#; + let dir = project(&[ + ("one/CMakeLists.txt", "project(one)"), + ("one/CMakePresets.json", presets), + ("two/CMakeLists.txt", "project(two)"), + ]); + let preset_configures = |configs: &[RunConfig]| -> Vec { + let mut ids: Vec<_> = + configs.iter().filter(|c| c.args.first().is_some_and(|a| a == "--preset")).map(|c| c.id.clone()).collect(); + ids.sort(); + ids + }; + // The settings' explicit profiles describe the root project only, never nested ones. + let settings = CMakeSettings { + profiles: Some(vec![CMakeProfile::default()]), + enabled_presets: vec!["dev".into()], + ..Default::default() + }; + let configs = ide_run::detect_with_cmake(dir.path(), &[], &settings, &[]); + let ids = preset_configures(&configs); + assert_eq!(ids.len(), 1, "{ids:?}"); + assert!(ids[0].contains("cmake:profile:configure") && ids[0].contains("one"), "{ids:?}"); + // Without presets, the nested project without any keeps the automatic discovery. + assert!(configs.iter().any(|c| c.id.contains("two") && c.args.first().is_some_and(|a| a == "-S"))); + // Presets are disabled until enabled (as in CLion), and can all be ignored. + for settings in [ + CMakeSettings { ignore_presets: true, enabled_presets: vec!["dev".into()], ..Default::default() }, + CMakeSettings::default(), + ] { + assert!(preset_configures(&ide_run::detect_with_cmake(dir.path(), &[], &settings, &[])).is_empty()); + } +} + +#[test] +fn saved_configurations_of_the_active_profile_keep_their_ids_from_before_the_switcher() { + use ide_core::settings::{CMakeProfile, CMakeSettings}; + let dir = project(&[("CMakeLists.txt", "project(app)\n")]); + let profile = |name: &str| CMakeProfile { name: name.into(), build_type: name.into(), ..Default::default() }; + let settings = CMakeSettings { + profiles: Some(vec![profile("Debug"), profile("Release")]), + active_profile: "Release".into(), + ..Default::default() + }; + cmake_reply(dir.path(), "cmake-build-release", &[("Release", &["app"])]); + fs::remove_file(dir.path().join("cmake-build-release/CMakeCache.txt")).unwrap(); + let detected = ide_run::detect_with_cmake(dir.path(), &[], &settings, &[]); + // Saved when every profile was detected: Release, the second profile, had `cmake:profile:1:`. + let mut build = find(&detected, "cmake:profile:build").clone(); + build.id = "cmake:profile:1:build".into(); + build.args.push("-j3".into()); + build.extras.before_launch[0].target = "cmake:profile:1:configure".into(); + let mut other = build.clone(); + other.id = "cmake:profile:0:build".into(); + let mut app = find(&detected, "cmake:profile:target:app").clone(); + app.id = "cmake:profile:1::app".into(); + app.extras.before_launch[0].target = "cmake:profile:1:Release:app:build".into(); + let mut saved = vec![build, other, app]; + let mut removed = + ["cmake:profile:1:test", "cmake:profile:0:test", "cmake:profile:1:Release:app:build"].map(String::from); + ide_run::upgrade_cmake_profile_ids(dir.path(), &settings, &mut saved, &mut removed); + assert_eq!(ids(&saved), ["cmake:profile:build", "cmake:profile:0:build", "cmake:profile:target:app"]); + assert_eq!(saved[0].extras.before_launch[0].target, "cmake:profile:configure"); + assert_eq!(saved[2].extras.before_launch[0].target, "cmake:profile:target:app:build"); + assert_eq!(removed, ["cmake:profile:test", "cmake:profile:0:test", "cmake:profile:target:app:build"]); + // The ids are the ones detection gives, so the customization replaces the detected one. + assert!(detected.iter().any(|c| c.id == saved[0].id)); + assert!(detected.iter().any(|c| c.id == saved[2].id)); + assert!(detected.iter().any(|c| c.id == removed[2])); + // Without saved profiles (automatic discovery or presets only) there were no such ids. + let presets = CMakeSettings { profiles: None, ..settings }; + let mut untouched = vec!["cmake:profile:0:test".to_owned()]; + ide_run::upgrade_cmake_profile_ids(dir.path(), &presets, &mut [], &mut untouched); + assert_eq!(untouched, ["cmake:profile:0:test"]); +} diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index 564b46461..cae24a934 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -885,6 +885,21 @@ mod tests { assert_eq!(SettingsStore::load(&cfg, Some(&proj)).named_removed_theme().as_deref(), Some("one-light")); } + #[test] + fn cmake_profiles_can_be_saved_next_to_the_other_cmake_settings() { + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(proj.join(".openidea")).unwrap(); + let store = SettingsStore::load(&tmp.path().join("cfg"), Some(&proj)); + store.set(SettingsScope::Project, "cmake.activeProfile", json!("Debug")).unwrap(); + store.set(SettingsScope::Project, "cmake.profiles", json!([{"name": "Debug", "enabled": true}])).unwrap(); + let cmake = SettingsStore::load(&tmp.path().join("cfg"), Some(&proj)).effective().cmake; + assert_eq!(cmake.profiles.unwrap()[0].name, "Debug"); + assert_eq!(cmake.active_profile, "Debug"); + store.set(SettingsScope::Project, "cmake.profiles", serde_json::Value::Null).unwrap(); + assert!(store.effective().cmake.profiles.is_none()); + } + #[test] fn compose_file_choices_are_project_settings_and_survive_reload() { let tmp = tempfile::tempdir().unwrap(); diff --git a/docs/en/languages/cpp.mdx b/docs/en/languages/cpp.mdx index e4295c082..c010b9ab0 100644 --- a/docs/en/languages/cpp.mdx +++ b/docs/en/languages/cpp.mdx @@ -70,27 +70,49 @@ For every `CMakeLists.txt` project, OpenIDEA creates run configurations: - **CMake Configure**: `cmake -S . -B -DCMAKE_EXPORT_COMPILE_COMMANDS=ON` (plus `-DCMAKE_BUILD_TYPE=Debug` for a new build directory). - **CMake Build**: `cmake --build `. It runs the configure step first when the build directory is not configured yet. - **CTest**: `ctest --test-dir --output-on-failure`, after a build. -- **Build <target>** and one run configuration per executable target. Running a target builds it first. +- **Build <target>** for every executable and library target (static, shared, module or object), and one run configuration per executable target. Running a target builds it first. -The executable targets come from CMake's File API, so they appear after the first configure. Nested CMake projects (for example in a folder that holds several repositories) get their own set of configurations. +The targets come from CMake's File API, so they appear after the first configure. Interface libraries, utility targets (such as Qt's `*_autogen`) and the targets CMake adds itself (`ZERO_CHECK`, `ALL_BUILD`) get no configuration. Nested CMake projects (for example in a folder that holds several repositories) get their own set of configurations. -Without profiles, the IDE uses every subdirectory of the project that contains a `CMakeCache.txt`, or `build/` when there is none. +Without saved profiles or enabled presets, the IDE uses every subdirectory of the project that contains a `CMakeCache.txt`, or `build/` when there is none. #### CMake profiles -To control the build directories yourself, add profiles in **Settings › Build, Execution, Deployment › CMake**. Each profile has: +To control the build directories yourself, add profiles in **Settings › Build, Execution, Deployment › CMake**, laid out as in CLion: one list holds the saved profiles and the presets, with **Add**, **Remove**, **Copy** (Ctrl+D), **Move Up** and **Move Down**. Each profile has: -| Field | Meaning | -| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -| Name | Shown next to the configuration names. | -| Build type | `Debug`, `Release`, `RelWithDebInfo` or `MinSizeRel` (passed as `CMAKE_BUILD_TYPE`). | -| Generator | Optional `-G` value, for example `Ninja`, `Unix Makefiles`, `Ninja Multi-Config`, `Visual Studio 17 2022` or `Xcode`. Empty uses CMake's default. | -| CMake arguments | Extra arguments for the configure step. | -| Build directory | Empty means `cmake-build-`, for example `cmake-build-debug`. | -| Build arguments | Extra arguments for `cmake --build`. | -| Environment variables | Set for configure, build, test and run. | +| Field | Meaning | +| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Enable profile | A disabled profile stays in the list, greyed, and is not used. | +| Name | Shown in the profile switcher. | +| Build type | `Debug`, `Release`, `RelWithDebInfo`, `MinSizeRel` or your own (passed as `CMAKE_BUILD_TYPE`). Empty is CLion's **Default**: no build type, no `--config`. | +| Toolchain | **Use Default** (the first toolchain) or one of [Toolchains](#toolchains). | +| Generator | Optional `-G` value, for example `Ninja`, `Unix Makefiles`, `MinGW Makefiles`, `Ninja Multi-Config`, `Visual Studio 17 2022` or `Xcode`. Empty lets CMake decide. | +| CMake options | Extra arguments for the configure step. | +| Build directory | Empty means `cmake-build-`, for example `cmake-build-debug` (`cmake-build-default` for the Default build type). | +| Build options | Extra arguments for `cmake --build`; arguments after `--` go to the native build tool. | +| Cache variables | The build directory's `CMakeCache.txt` once configured (**Show advanced** for all). Editing a value adds `-DNAME:TYPE=value` to the CMake options, shown in bold; **Revert** removes it. | +| Environment | Set for configure, build, test and run. | -Once profiles exist, only they are used. Changing the generator of an existing build directory clears its CMake cache on the next configure. +As in CLion, only the **active profile** builds and runs. Pick it in the profile switcher of the title bar, next to the run configuration chooser (or with **Select CMake Profile…**); without a choice the first enabled profile is active. The run configurations keep the same ids whichever profile is active, so their customizations follow a switch. Changing the generator of an existing build directory clears its CMake cache on the next configure. + +#### CMake presets + +A `CMakePresets.json` or `CMakeUserPresets.json` at the project root lists each visible configure preset whose `condition` holds after the saved profiles. As in CLion, a preset is read-only and **disabled until you enable it**; copy it to get an editable profile. + +- **CMake Configure** runs `cmake --preset -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`. The preset's `binaryDir` is the build directory; without one, the IDE adds `-B build/`. +- **CMake Build** and **Build <target>** run `cmake --build --preset ` with the first build preset of that configure preset. Without one they build the directory, like a profile. +- **CTest** runs `ctest --preset ` the same way. +- The preset's `environment` is set for the run configurations too. Its `CMAKE_BUILD_TYPE`, else the `configuration` of its build preset (multi-config generators), picks the configuration of the targets (default `Debug`). +- CLion's vendor field picks the toolchain: `"vendor": { "jetbrains.com/clion": { "toolchain": "MinGW" } }`. +- Nested CMake projects use their own presets; the profiles of the settings only apply to the root project. + +The IDE follows `include`, `inherits` and conditions (`equals`, `inList`, `matches`, `anyOf`, `not`…), and expands macros such as `${sourceDir}`, `${presetName}` and `$env{NAME}`. A file it cannot read (invalid JSON, duplicate names, inheritance cycle) is skipped, and the CMake settings page shows why. **Use CMakePresets.json** turns presets off altogether. + +#### Toolchains + +**Settings › Build, Execution, Deployment › Toolchains** lists the toolchains for every project; the first is the default. A toolchain is **System** (tools from the paths you give, else from `PATH`) or **MinGW** (a MinGW or MSYS2 directory: its `bin` goes first on `PATH`, with `gcc`, `g++`, `mingw32-make` and `gdb` from there, and the `MinGW Makefiles` generator unless the build tool is Ninja). **Detect MinGW** adds the MSYS2 environments and MinGW installs found in their usual places. + +Each tool can be set: **CMake** (configure, build, and the `ctest` next to it), **Build Tool** (`CMAKE_MAKE_PROGRAM`), **C Compiler** and **C++ Compiler** (`CMAKE_C_COMPILER`, `CMAKE_CXX_COMPILER`), and **Debugger** (preferred over lldb-dap for the profile's run configurations). Under each one the page shows the executable it resolves to and its version. A toolchain never overrides what the profile sets itself: a variable among its CMake options or its preset's `cacheVariables`, the compilers and build tool when it names a toolchain file, and the build tool when its generator cannot use it (Visual Studio, Xcode, or Ninja with a make). ### Makefiles diff --git a/docs/zh/languages/cpp.mdx b/docs/zh/languages/cpp.mdx index 1c65d9dd3..c2bcb84d9 100644 --- a/docs/zh/languages/cpp.mdx +++ b/docs/zh/languages/cpp.mdx @@ -70,27 +70,49 @@ Xcode 和 Command Line Tools 自带的 `clangd` 不运行 clang-tidy。如果项 - **CMake Configure**:`cmake -S . -B <构建目录> -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`(新构建目录还会加上 `-DCMAKE_BUILD_TYPE=Debug`)。 - **CMake Build**:`cmake --build <构建目录>`,构建目录尚未配置时会先执行配置步骤。 - **CTest**:先构建,再执行 `ctest --test-dir <构建目录> --output-on-failure`。 -- **Build <目标>**,以及每个可执行目标各一个运行配置。运行目标前会先构建它。 +- **Build <目标>**:每个可执行目标和库目标(静态库、共享库、模块库、对象库)各一个;另外每个可执行目标还有一个运行配置。运行目标前会先构建它。 -可执行目标来自 CMake 的 File API,因此要在第一次配置之后才会出现。嵌套的 CMake 项目(例如一个文件夹里放了多个仓库)各自生成一套配置。 +目标来自 CMake 的 File API,因此要在第一次配置之后才会出现。接口库、工具目标(例如 Qt 的 `*_autogen`)以及 CMake 自己添加的目标(`ZERO_CHECK`、`ALL_BUILD`)不会生成配置。嵌套的 CMake 项目(例如一个文件夹里放了多个仓库)各自生成一套配置。 -没有配置 CMake 配置文件时,IDE 使用项目中所有含 `CMakeCache.txt` 的子目录;一个都没有时使用 `build/`。 +没有已保存的配置也没有启用的预设时,IDE 使用项目中所有含 `CMakeCache.txt` 的子目录;一个都没有时使用 `build/`。 #### CMake 配置 -如果想自己控制构建目录,在 **设置 › 构建、执行、部署 › CMake** 中添加配置(界面上叫“CMake 配置”)。每个配置包含: +要自己控制构建目录,可在 **设置 › 构建、执行、部署 › CMake** 中添加配置。页面布局与 CLion 相同:同一个列表包含已保存的配置和预设,提供 **添加**、**移除**、**复制**(Ctrl+D)、**上移**、**下移**。每个配置包含: -| 字段 | 含义 | -| ---------- | --------------------------------------------------------------------------------------------------------------------------------- | -| 名称 | 显示在运行配置名称后面。 | -| 构建类型 | `Debug`、`Release`、`RelWithDebInfo` 或 `MinSizeRel`(作为 `CMAKE_BUILD_TYPE` 传入)。 | -| 生成器 | 可选的 `-G` 参数,例如 `Ninja`、`Unix Makefiles`、`Ninja Multi-Config`、`Visual Studio 17 2022`、`Xcode`。留空使用 CMake 默认值。 | -| CMake 参数 | 配置步骤的额外参数。 | -| 构建目录 | 留空表示 `cmake-build-<构建类型>`,例如 `cmake-build-debug`。 | -| 构建参数 | `cmake --build` 的额外参数。 | -| 环境变量 | 配置、构建、测试和运行时都会设置。 | +| 字段 | 含义 | +| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 启用配置 | 停用的配置仍留在列表中(灰色显示),但不会被使用。 | +| 名称 | 显示在配置切换器中。 | +| 构建类型 | `Debug`、`Release`、`RelWithDebInfo`、`MinSizeRel` 或自定义类型(作为 `CMAKE_BUILD_TYPE` 传入)。留空即 CLion 的 **Default**:不设构建类型,也不传 `--config`。 | +| 工具链 | **使用默认值**(第一个工具链)或某个[工具链](#工具链)。 | +| 生成器 | 可选的 `-G` 值,例如 `Ninja`、`Unix Makefiles`、`MinGW Makefiles`、`Ninja Multi-Config`、`Visual Studio 17 2022` 或 `Xcode`。留空由 CMake 决定。 | +| CMake 选项 | 配置步骤的额外参数。 | +| 构建目录 | 留空表示 `cmake-build-<构建类型>`,例如 `cmake-build-debug`(Default 构建类型为 `cmake-build-default`)。 | +| 构建选项 | `cmake --build` 的额外参数;`--` 之后的参数传给原生构建工具。 | +| 缓存变量 | 配置后构建目录中的 `CMakeCache.txt`(勾选 **显示高级** 可看全部)。修改某个值会在 CMake 选项中加入 `-DNAME:TYPE=value`,并以粗体显示;**还原** 会将其移除。 | +| 环境 | 用于配置、构建、测试和运行。 | -一旦添加了配置,就只使用这些配置。修改已有构建目录的生成器后,下次配置时会清掉它的 CMake 缓存。 +与 CLion 一样,只有**当前配置**会参与构建和运行。可在标题栏中运行配置选择器旁边的配置切换器里选择(或使用 **选择 CMake 配置…**);未选择时使用第一个启用的配置。无论当前是哪个配置,运行配置的 ID 都保持不变,因此切换后自定义设置依然有效。修改已有构建目录的生成器后,下次配置时会清掉它的 CMake 缓存。 + +#### CMake 预设 + +项目根目录的 `CMakePresets.json` 或 `CMakeUserPresets.json` 中,每个可见且 `condition` 成立的配置预设都会列在已保存的配置之后。与 CLion 一样,预设是只读的,并且**在启用之前处于停用状态**;复制预设即可得到可编辑的配置。 + +- **CMake Configure** 执行 `cmake --preset <名称> -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`。构建目录是预设的 `binaryDir`;没有时 IDE 会加上 `-B build/<名称>`。 +- **CMake Build** 和 **Build <目标>** 使用该配置预设的第一个构建预设执行 `cmake --build --preset <构建预设>`;没有构建预设时,像普通配置一样构建目录。 +- **CTest** 以同样的方式执行 `ctest --preset <测试预设>`。 +- 预设的 `environment` 也会用于运行配置。目标使用的构建类型取自其 `CMAKE_BUILD_TYPE`,没有时取其构建预设的 `configuration`(多配置生成器),默认 `Debug`。 +- CLion 的 vendor 字段可指定工具链:`"vendor": { "jetbrains.com/clion": { "toolchain": "MinGW" } }`。 +- 嵌套的 CMake 项目使用各自的预设;设置中的配置只用于根项目。 + +IDE 支持 `include`、`inherits` 和各种条件(`equals`、`inList`、`matches`、`anyOf`、`not` 等),并展开 `${sourceDir}`、`${presetName}`、`$env{NAME}` 等宏。无法读取的文件(JSON 无效、名称重复、继承成环)会被跳过,CMake 设置页面会显示原因。**使用 CMakePresets.json** 可完全关闭预设。 + +#### 工具链 + +**设置 › 构建、执行、部署 › 工具链** 列出所有项目共用的工具链,第一个为默认工具链。工具链分为 **System**(使用指定路径中的工具,否则使用 `PATH` 中的工具)和 **MinGW**(MinGW 或 MSYS2 目录:其 `bin` 放在 `PATH` 最前面,`gcc`、`g++`、`mingw32-make` 和 `gdb` 都取自该目录;除非构建工具是 Ninja,否则使用 `MinGW Makefiles` 生成器)。**检测 MinGW** 会添加在常见位置找到的 MSYS2 环境和 MinGW 安装。 + +每个工具都可以单独设置:**CMake**(用于配置、构建,以及同目录下的 `ctest`)、**构建工具**(`CMAKE_MAKE_PROGRAM`)、**C 编译器**和 **C++ 编译器**(`CMAKE_C_COMPILER`、`CMAKE_CXX_COMPILER`),以及**调试器**(该配置的运行配置会优先使用它,而不是 lldb-dap)。页面会在每个工具下方显示解析到的可执行文件及其版本。工具链不会覆盖配置自身设置的内容:其 CMake 选项或预设 `cacheVariables` 中的变量;配置指定了工具链文件时的编译器和构建工具;以及生成器无法使用该构建工具时的构建工具(Visual Studio、Xcode,或 Ninja 搭配 make)。 ### Makefile diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 2efcf8503..59c883ae1 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -140,6 +140,8 @@ clipboard_text always desktop bin clipboard_write_image always desktop bindings async clipboard_write_text always desktop bindings async close_project always project_host bindings spawn +cmake_cache always project_host bindings async +cmake_profiles always project_host bindings async coverage_collect trusted project_host bindings async coverage_import always project_host bindings async coverage_prepare trusted project_host bindings async @@ -800,6 +802,8 @@ term_resize always project_host bin term_spawn always project_host bindings async term_store_image always project_host bindings async term_write always project_host bindings sync +toolchain_check always project_host bindings async +toolchains_detect always project_host bindings async tools_install outside_restricted project_host bindings async tools_list outside_restricted project_host bindings async tools_uninstall outside_restricted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 30ae45465..2814c40a3 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -433,6 +433,13 @@ export const commands = { /** Writes text locally, without WebView user-activation requirements. */ clipboardWriteText: (text: string) => typedError(__TAURI_INVOKE("clipboard_write_text", { text })), closeProject: () => __TAURI_INVOKE("close_project"), + /** + * Settings › CMake › Cache variables: the `CMakeCache.txt` of `build_dir` (relative to the + * project, or absolute), empty while that directory is not configured. Reading runs nothing. + */ + cmakeCache: (buildDir: string) => typedError(__TAURI_INVOKE("cmake_cache", { buildDir })), + /** Reading the profiles runs nothing, so an untrusted project lists them too. */ + cmakeProfiles: () => typedError(__TAURI_INVOKE("cmake_profiles")), /** Reads the report a coverage run left behind. */ coverageCollect: (report: CoverageReportSpec) => typedError(__TAURI_INVOKE("coverage_collect", { report })), /** @@ -2406,6 +2413,13 @@ export const commands = { termSpawn: (options: TerminalOptions, onOutput: Channel) => typedError(__TAURI_INVOKE("term_spawn", { options, onOutput })), termStoreImage: (id: TerminalId, data: IpcBytes, mime: string) => typedError(__TAURI_INVOKE("term_store_image", { id, data, mime })), termWrite: (id: TerminalId, data: string) => typedError(__TAURI_INVOKE("term_write", { id, data })), + /** + * Settings › Toolchains: which executable each tool of `toolchain` resolves to, and its version. + * Only `--version` runs; the settings are IDE-wide, so no project needs to be trusted. + */ + toolchainCheck: (toolchain: Toolchain) => typedError<{ [key in string]: ToolCheck }, IdeError>(__TAURI_INVOKE("toolchain_check", { toolchain })), + /** Settings › Toolchains: a toolchain for each MinGW / MSYS2 install found (Windows). */ + toolchainsDetect: () => typedError(__TAURI_INVOKE("toolchains_detect")), /** * Installs (or reinstalls) a tool into `/tools`, streaming output through * `on_event`. Cancel with `cancel_request(request)`. @@ -5887,7 +5901,54 @@ export type ByteRange = { total: number, }; -export type CMakeProfile = { +/** The presets a profile made from `CMakePresets.json` runs with. */ +export type CMakePresetRef = CMakePresetRef_Serialize | CMakePresetRef_Deserialize; + +/** The presets a profile made from `CMakePresets.json` runs with. */ +export type CMakePresetRef_Deserialize = { + configure?: string, + /** The first build preset of `configure`, used by `cmake --build --preset`. */ + build?: string | null, + /** The first test preset of `configure`, used by `ctest --preset`. */ + test?: string | null, +}; + +/** The presets a profile made from `CMakePresets.json` runs with. */ +export type CMakePresetRef_Serialize = { + configure: string, + /** The first build preset of `configure`, used by `cmake --build --preset`. */ + build?: string | null, + /** The first test preset of `configure`, used by `ctest --preset`. */ + test?: string | null, +}; + +export type CMakeProfile = CMakeProfile_Serialize | CMakeProfile_Deserialize; + +/** + * Settings › CMake and the toolbar switcher: every profile, saved ones then presets (with + * whether each is enabled), and why the presets file cannot be read, if it cannot. + */ +export type CMakeProfileList = CMakeProfileList_Serialize | CMakeProfileList_Deserialize; + +/** + * Settings › CMake and the toolbar switcher: every profile, saved ones then presets (with + * whether each is enabled), and why the presets file cannot be read, if it cannot. + */ +export type CMakeProfileList_Deserialize = { + profiles: CMakeProfile_Deserialize[], + presetsError: string | null, +}; + +/** + * Settings › CMake and the toolbar switcher: every profile, saved ones then presets (with + * whether each is enabled), and why the presets file cannot be read, if it cannot. + */ +export type CMakeProfileList_Serialize = { + profiles: CMakeProfile_Serialize[], + presetsError: string | null, +}; + +export type CMakeProfile_Deserialize = { name?: string, buildType?: string, generator?: string, @@ -5896,6 +5957,35 @@ export type CMakeProfile = { buildDir?: string, buildArgs?: string[], env?: { [key in string]: string }, + /** `false` keeps the profile listed but unused (CLion's "Enable profile"). */ + enabled?: boolean, + /** Toolchain name (Settings › Toolchains); empty = the default (first) toolchain. */ + toolchain?: string, + /** + * Set only on the profiles made from presets: configure with `cmake --preset`, and the + * generator and cache variables come from the preset. + */ + preset?: CMakePresetRef_Deserialize | null, +}; + +export type CMakeProfile_Serialize = { + name: string, + buildType: string, + generator: string, + cmakeArgs: string[], + /** Empty uses cmake-build-. */ + buildDir: string, + buildArgs: string[], + env: { [key in string]: string }, + /** `false` keeps the profile listed but unused (CLion's "Enable profile"). */ + enabled: boolean, + /** Toolchain name (Settings › Toolchains); empty = the default (first) toolchain. */ + toolchain: string, + /** + * Set only on the profiles made from presets: configure with `cmake --preset`, and the + * generator and cache variables come from the preset. + */ + preset?: CMakePresetRef_Serialize | null, }; /** Absent profiles retain automatic discovery for existing projects. */ @@ -5903,12 +5993,51 @@ export type CMakeSettings = CMakeSettings_Serialize | CMakeSettings_Deserialize; /** Absent profiles retain automatic discovery for existing projects. */ export type CMakeSettings_Deserialize = { - profiles?: CMakeProfile[] | null, + profiles?: CMakeProfile_Deserialize[] | null, + /** + * `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible + * configure preset whose condition holds is listed after the explicit profiles. + */ + ignorePresets?: boolean, + /** + * Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but + * disabled until enabled here. + */ + enabledPresets?: string[], + /** + * The profile (by name) that build, run and debug use, as CLion's toolbar switcher; + * empty or unknown = the first enabled one. + */ + activeProfile?: string, }; /** Absent profiles retain automatic discovery for existing projects. */ export type CMakeSettings_Serialize = { - profiles?: CMakeProfile[] | null, + profiles?: CMakeProfile_Serialize[] | null, + /** + * `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible + * configure preset whose condition holds is listed after the explicit profiles. + */ + ignorePresets: boolean, + /** + * Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but + * disabled until enabled here. + */ + enabledPresets: string[], + /** + * The profile (by name) that build, run and debug use, as CLion's toolbar switcher; + * empty or unknown = the first enabled one. + */ + activeProfile: string, +}; + +export type CacheEntry = { + name: string, + /** `BOOL`, `STRING`, `PATH`, `FILEPATH`… */ + kind: string, + value: string, + help: string, + advanced: boolean, }; /** @@ -16049,6 +16178,8 @@ export type Settings_Deserialize = { /** Build, Execution, Deployment › Run Targets. */ runTargets?: RunTarget[], cmake?: CMakeSettings_Deserialize, + /** Build, Execution, Deployment › Toolchains; the first is the default. */ + toolchains?: Toolchain[], /** Settings › Agents. */ agents?: AgentSettings_Deserialize, /** Agents › MCP Server (global only). */ @@ -16130,6 +16261,8 @@ export type Settings_Serialize = { /** Build, Execution, Deployment › Run Targets. */ runTargets: RunTarget[], cmake: CMakeSettings_Serialize, + /** Build, Execution, Deployment › Toolchains; the first is the default. */ + toolchains: Toolchain[], /** Settings › Agents. */ agents: AgentSettings_Serialize, /** Agents › MCP Server (global only). */ @@ -17130,6 +17263,16 @@ export type ToolCallDisplay = /** Each call on its own line. */ "each"; +/** + * One tool of a toolchain as Settings › Toolchains shows it: the executable used (chosen, from the + * MinGW directory, else found on `PATH`) and its version, or why it cannot be used. + */ +export type ToolCheck = { + path: string | null, + version: string | null, + problem: string | null, +}; + /** * Tools › Download sources: mirrors the installer tries, in order, when `github.com` is slow * or unreachable. @@ -17226,6 +17369,32 @@ export type ToolUpdate = { latest: string, }; +/** + * Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are + * detected: from the MinGW directory, else from `PATH`. + */ +export type Toolchain = { + name?: string, + kind?: ToolchainKind, + /** The MinGW directory (the one holding `bin`). */ + path?: string, + cmake?: string, + /** `CMAKE_MAKE_PROGRAM`: make, mingw32-make or ninja. */ + buildTool?: string, + cCompiler?: string, + cxxCompiler?: string, + debugger?: string, +}; + +export type ToolchainKind = +/** Tools from the chosen paths, else from `PATH`. */ +"system" | +/** + * A MinGW / MSYS2 directory: its `bin` goes first on `PATH`, with gcc, g++, + * mingw32-make and gdb from there. + */ +"mingw"; + /** Something the user must know to read the trace correctly. */ export type TraceBanner = { kind: "truncated"; dropped: number } | /** `count()` on a sized source skips the pipeline, so nothing was recorded. */ diff --git a/src/features/debugger/launch.ts b/src/features/debugger/launch.ts index 537680dc8..ac4555b29 100644 --- a/src/features/debugger/launch.ts +++ b/src/features/debugger/launch.ts @@ -415,6 +415,8 @@ function nativeLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig out.extraJson = JSON.stringify({ env: Object.entries(rc.env).map(([k, v]) => `${k}=${v}`), ...(swiftpm ? { swiftpm } : {}), + // The debugger of the CMake profile's toolchain (a MinGW gdb): the backend runs it. + ...(rc.params?.debugger ? { __adapterCommand: rc.params.debugger } : {}), ...(from && to && from !== to ? { sourceMap: [[from, to]] } : {}), }); } else if (rc.kind === "zig-application" || rc.params?.language === "zig") { diff --git a/src/features/run/CMakeProfileChooser.test.tsx b/src/features/run/CMakeProfileChooser.test.tsx new file mode 100644 index 000000000..e96882c3d --- /dev/null +++ b/src/features/run/CMakeProfileChooser.test.tsx @@ -0,0 +1,78 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import type { ProjectInfo, RunConfig } from "@/platform/ipc"; +import { commands } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { + activeCMakeProfile, + CMakeProfileChooser, + selectCMakeProfile, + toggleCMakeProfiles, + useCMakeProfiles, +} from "./CMakeProfileChooser"; +import { resetRuns, useRun } from "./store"; + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + commands: { + ...real.commands, + cmakeProfiles: vi.fn(async () => ({ + status: "ok", + data: { + profiles: [ + { name: "Debug", enabled: true }, + { name: "Off", enabled: false }, + { name: "dev", enabled: true, preset: { configure: "dev" } }, + ], + presetsError: null, + }, + })), + settingsSet: vi.fn(async () => ({ status: "ok", data: { cmake: { activeProfile: "dev" } } })), + }, + }; +}); + +const cmake = (profile: string): RunConfig => ({ + id: "cmake:profile:build", + name: "CMake Build", + kind: "cmake", + command: "cmake", + args: ["--build", "build"], + cwd: null, + env: {}, + detected: true, + isTest: false, + debugAdapter: null, + params: { cmakeProfile: profile }, +}); + +beforeEach(() => { + resetRuns(); + useCMakeProfiles.setState({ open: false, profiles: null, problem: null }); + useProject.setState({ project: { root: "/p" } as ProjectInfo }); +}); +afterEach(cleanup); + +it("shows the active profile only in projects whose configurations come from one", () => { + useRun.setState({ configs: [{ ...cmake("x"), params: {} }] }); + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + act(() => useRun.setState({ configs: [cmake("Debug")] })); + expect(screen.getByRole("button", { name: "CMake profile: Debug" })).toBeInTheDocument(); + expect(activeCMakeProfile([cmake("Release")])).toBe("Release"); +}); + +it("lists the enabled profiles and switches the active one", async () => { + useRun.setState({ configs: [cmake("Debug")] }); + render(); + await act(() => toggleCMakeProfiles()); + expect(useCMakeProfiles.getState().profiles?.map((p) => p.name)).toEqual(["Debug", "dev"]); + expect(screen.getByRole("menuitemcheckbox", { name: "Debug" })).toHaveAttribute("aria-checked", "true"); + expect(screen.queryByText("Off")).toBeNull(); + fireEvent.click(screen.getByRole("menuitemcheckbox", { name: "dev" })); + await act(() => selectCMakeProfile("dev")); + expect(commands.settingsSet).toHaveBeenCalledWith("project", "cmake.activeProfile", JSON.stringify("dev")); + expect(useCMakeProfiles.getState().open).toBe(false); +}); diff --git a/src/features/run/CMakeProfileChooser.tsx b/src/features/run/CMakeProfileChooser.tsx new file mode 100644 index 000000000..04eefad1e --- /dev/null +++ b/src/features/run/CMakeProfileChooser.tsx @@ -0,0 +1,103 @@ +import { useRef } from "react"; +import { create } from "zustand"; +import type { CMakeProfile_Serialize as CMakeProfile } from "@/bindings"; +import { BarButton, Icon, Menu, type MenuItem } from "@/ui"; +import { executeAction } from "@/platform/actions"; +import { useTx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { useRun } from "./store"; +import styles from "./Run.module.css"; + +interface ProfileChooserState { + open: boolean; + /** The enabled profiles, loaded when the menu opens (saved ones, then presets). */ + profiles: CMakeProfile[] | null; + problem: string | null; +} + +export const useCMakeProfiles = create(() => ({ open: false, profiles: null, problem: null })); + +/** The profile the detected CMake configurations come from (only the active one is detected). */ +export function activeCMakeProfile(configs: { params?: Record | null }[]): string | null { + return configs.find((c) => c.params?.cmakeProfile)?.params?.cmakeProfile ?? null; +} + +/** Opens (or closes) the menu, listing the enabled profiles afresh. */ +export async function toggleCMakeProfiles(): Promise { + const open = !useCMakeProfiles.getState().open; + useCMakeProfiles.setState({ open }); + if (!open) return; + try { + const { profiles } = await call(commands.cmakeProfiles()); + useCMakeProfiles.setState({ + profiles: (profiles as CMakeProfile[]).filter((p) => p.enabled !== false), + problem: null, + }); + } catch (e) { + useCMakeProfiles.setState({ profiles: [], problem: e instanceof Error ? e.message : String(e) }); + } +} + +/** Makes `name` the active profile: the configurations are detected again from it. */ +export async function selectCMakeProfile(name: string): Promise { + const project = useProject.getState().project; + useCMakeProfiles.setState({ open: false }); + if (!project) return; + const settings = await call(commands.settingsSet("project", "cmake.activeProfile", JSON.stringify(name))); + if (useProject.getState().project === project) useProject.setState({ settings }); +} + +/** Title bar: CLion's CMake profile switcher, in projects whose configurations come from a profile. */ +export function CMakeProfileChooser() { + const active = useRun((s) => activeCMakeProfile(s.configs)); + return active ? : null; +} + +function Chooser({ active }: { active: string }) { + const tx = useTx(); + const anchor = useRef(null); + const { open, profiles, problem } = useCMakeProfiles(); + const items: MenuItem[] = [ + { kind: "header", label: tx("CMake Profile") }, + ...(profiles ?? []).map((p): MenuItem => ({ + id: `profile:${p.name}`, + label: p.name, + verbatim: true, + checked: p.name === active, + run: () => void executeAction("run.cmakeSelectProfile", p.name), + })), + ...(profiles === null ? [{ label: tx("Loading…"), disabled: true }] : []), + ...(problem ? [{ label: problem, verbatim: true, disabled: true }] : []), + { kind: "separator" }, + { kind: "action", action: "run.cmakeSettings" }, + ]; + return ( + <> + void executeAction("run.cmakeChooseProfile")} + > + + + {active} + + + + useCMakeProfiles.setState({ open: false })} + /> + + ); +} diff --git a/src/features/run/RunWidget.test.tsx b/src/features/run/RunWidget.test.tsx index 411dc4aca..274ea36b8 100644 --- a/src/features/run/RunWidget.test.tsx +++ b/src/features/run/RunWidget.test.tsx @@ -136,6 +136,20 @@ it("offers Run/Debug for an idle selection and Stop for the other process", () = expect(useRun.getState().sessions[0]?.stopped).toBe(true); }); +it("offers Stop while a build runs in the Build window, as CLion", () => { + const stopBuild = vi.fn(); + const unregister = registerAction({ id: "build.stop", title: "Stop Build", run: stopBuild }); + setContext("build.running", true); + try { + render(); + fireEvent.click(screen.getByRole("button", { name: "Stop 'Build'" })); + expect(stopBuild).toHaveBeenCalled(); + } finally { + setContext("build.running", false); + unregister(); + } +}); + it("offers a stop list when the selection is idle and several other sessions run", () => { useRun.setState({ sessions: [run(npm), run(config("other"))] }); render(); diff --git a/src/features/run/RunWidget.tsx b/src/features/run/RunWidget.tsx index 6c6d931e7..fc042baa8 100644 --- a/src/features/run/RunWidget.tsx +++ b/src/features/run/RunWidget.tsx @@ -2,10 +2,12 @@ import { useRef, useState } from "react"; import clsx from "clsx"; import { BarButton, Icon, IconButton, Menu, Spinner, type MenuItem } from "@/ui"; import { executeAction } from "@/platform/actions"; +import { useContextKeys } from "@/platform/context"; import { useTx } from "@/platform/i18n"; import { shortcutLabel } from "@/platform/keymap"; import { runExecutors, useRunExecutors, useDebugRunSessions } from "@/workbench/contributions"; import { configIcon } from "./configs"; +import { CMakeProfileChooser } from "./CMakeProfileChooser"; import { FlutterDeviceChooser } from "./FlutterDeviceChooser"; import { IosSimulatorChooser } from "./IosSimulatorChooser"; import { useRemoteLabel } from "./remote"; @@ -33,7 +35,10 @@ export function RunWidget() { const compoundRunning = compoundTargets(selected, running, debug); const target = selectedTarget(selectedId, running, debug); const { active, debugging, showLoading, launch } = useLaunchFeedback(selectedId, target, compoundRunning); - const count = running.length + debug.length; + // A build (Build Project, or a CMake build configuration) runs in the Build window: Stop + // reaches it too, as in CLion. + const building = useContextKeys((s) => !!s["build.running"]); + const count = running.length + debug.length + (building ? 1 : 0); const stopping = running.some((s) => s.status === "stopping") || debug.some((s) => s.status === "stopping"); const stop = () => void executeAction("run.stop", "widget"); const targetStopping = @@ -41,7 +46,7 @@ export function RunWidget() { debug.some((s) => s.status === "stopping" && s.configId === selectedId); const stopName = compoundRunning.length ? selected?.name - : (target?.name ?? running[0]?.config.name ?? debug[0]?.name); + : (target?.name ?? running[0]?.config.name ?? debug[0]?.name ?? (building ? tx("Build") : undefined)); const moreRef = useRef(null); const [moreOpen, setMoreOpen] = useState(false); const executors = useRunExecutors((s) => s.executors); @@ -63,6 +68,7 @@ export function RunWidget() { return (
+ { + const start = vi.fn(async () => null); + const stale = { + ...config("cmake:profile:configure", "cmake", ["--preset", "dev"]), + params: { [NEEDS_CONFIGURE]: "true" }, + }; + const configs = [stale, config("cmake:profile:build", "cmake", ["--build", "out"])]; + reloadCMakeProjects("/reload", configs, start); + reloadCMakeProjects("/reload", configs, start); + expect(start).toHaveBeenCalledTimes(1); + expect(start).toHaveBeenCalledWith(stale); + // Another command (a profile switch, edited options) is tried again. + reloadCMakeProjects("/reload", [{ ...stale, args: ["--preset", "release"] }], start); + expect(start).toHaveBeenCalledTimes(2); +}); diff --git a/src/features/run/cmake.ts b/src/features/run/cmake.ts index f00d93201..14f5c1a0c 100644 --- a/src/features/run/cmake.ts +++ b/src/features/run/cmake.ts @@ -24,3 +24,28 @@ export function cmakeBuildId(config: RunConfig | undefined, configs: readonly Ru export async function buildCMake(id: string, activate = false): Promise { return buildTask("build.buildProject", { cmake: id, activate }); } + +/** Param of a configure configuration whose build directory has no CMake File API reply yet. */ +export const NEEDS_CONFIGURE = "cmakeNeedsConfigure"; + +const reloaded = new Set(); + +/** + * CLion reloads the CMake project on its own: the configure configurations whose build directory + * CMake never described (`NEEDS_CONFIGURE`) run once in the background, after which the + * project's executables and libraries are detected. A failed configure is not retried until its + * command changes; the configurations only load in a trusted project. + */ +export function reloadCMakeProjects( + root: string, + configs: readonly RunConfig[], + start: (config: RunConfig) => Promise, +): void { + for (const config of configs) { + if (config.params?.[NEEDS_CONFIGURE] !== "true") continue; + const key = JSON.stringify([root, config.id, config.command, config.args, config.env]); + if (reloaded.has(key)) continue; + reloaded.add(key); + void start(config).catch(() => {}); + } +} diff --git a/src/features/run/index.ts b/src/features/run/index.ts index 8bc5cd13c..951a1e245 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -88,6 +88,8 @@ import { } from "./applicationUpdate"; import { hotReload, hotReloadSession, hotRestart, syncFlutterRunApps } from "./flutterHotReload"; import { registerFlutterBuildActions } from "./flutterBuild"; +import { selectCMakeProfile, toggleCMakeProfiles } from "./CMakeProfileChooser"; +import { reloadCMakeProjects } from "./cmake"; import { registerXcodeCleanActions } from "./xcodeClean"; import { npmGutter } from "./npmGutter"; import { launchSettingsGutter } from "./launchSettingsGutter"; @@ -395,6 +397,10 @@ function stopAction(arg?: unknown) { run: () => void stopSession(s.id), })), ...menuGroupItems("stopProcess", { paths: [] }), + // The build running in the Build window (Build Project, a CMake build configuration). + ...(ctx["build.running"] && getAction("build.stop") + ? [{ label: "Build", icon: "build-project", run: () => void executeAction("build.stop") }] + : []), ].filter((i): i is MenuItem & { run: () => void } => "run" in i && !!i.run); // A Debug launch has no Run process: with nothing else to stop, the title-bar Stop reaches // the debug session itself (the Debug window need not be focused). @@ -642,6 +648,33 @@ export function activate(): () => void { when: "projectOpen && activeToolWindow == 'run'", run: () => rerunActive(), }, + { + id: "run.cmakeChooseProfile", + title: "Select CMake Profile…", + category: "Run", + keywords: ["cmake", "profile", "preset", "build type"], + run: () => void toggleCMakeProfiles(), + }, + { + id: "run.cmakeSelectProfile", + title: "Use CMake Profile", + category: "Run", + hidden: true, + run: async ({ arg }) => { + if (typeof arg !== "string" || !arg) return; + try { + await selectCMakeProfile(arg); + } catch (e) { + notifications().notify({ level: "error", title: "Cannot select the CMake profile", body: String(e) }); + } + }, + }, + { + id: "run.cmakeSettings", + title: "CMake Settings…", + category: "Run", + run: () => void executeAction("file.settings", "build.cmake"), + }, { id: "run.flutterChooseDevice", title: "Select Flutter Device…", @@ -1080,6 +1113,13 @@ export function activate(): () => void { useContextKeys.subscribe((s, prev) => { if (prev["build.running"] && !s["build.running"]) scheduleReload(); }), + // CMake build directories never described by CMake are configured once, so their targets show up. + useRun.subscribe((s, prev) => { + const root = useProject.getState().project?.root; + if (root && s.configs !== prev.configs) { + reloadCMakeProjects(root, s.configs, (config) => startRun(config, undefined, undefined, { show: false })); + } + }), onIdeEvent("runExited", (e) => { if (useRun.getState().sessions.some((s) => s.runId === e.run && s.config.kind === "cmake")) scheduleReload(); }), @@ -1090,7 +1130,9 @@ export function activate(): () => void { e.key === "languages" || e.key.startsWith("languages.") || e.key === "cmake" || - e.key.startsWith("cmake.") + e.key.startsWith("cmake.") || + e.key === "toolchains" || + e.key.startsWith("toolchains.") ) scheduleReload(); }), diff --git a/src/features/settings/__tests__/cmake.test.ts b/src/features/settings/__tests__/cmake.test.ts index bf5da3a79..580f65584 100644 --- a/src/features/settings/__tests__/cmake.test.ts +++ b/src/features/settings/__tests__/cmake.test.ts @@ -7,6 +7,12 @@ describe("CMake settings", () => { expect(validateSettings({}).cmake).toEqual({}); expect(validateSettings({ cmake: { profiles: [] } }).cmake.profiles).toEqual([]); }); + it("keeps the preset choices and drops malformed ones", () => { + expect( + validateSettings({ cmake: { ignorePresets: true, enabledPresets: ["dev", 3], activeProfile: "dev" } }).cmake, + ).toEqual({ ignorePresets: true, enabledPresets: ["dev"], activeProfile: "dev" }); + expect(validateSettings({ cmake: { ignorePresets: "yes" } }).cmake).toEqual({}); + }); it("preserves argument arrays and drops malformed argument values", () => { const cmakeArgs = ["-DMESSAGE=two words", '-DQUOTE="hello"', ""]; const buildArgs = ["-j", "8", "--", "LABEL=it's a build"]; diff --git a/src/features/settings/__tests__/cmakeEditor.test.tsx b/src/features/settings/__tests__/cmakeEditor.test.tsx index 7a7a9db02..b03dbebba 100644 --- a/src/features/settings/__tests__/cmakeEditor.test.tsx +++ b/src/features/settings/__tests__/cmakeEditor.test.tsx @@ -1,23 +1,58 @@ -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { afterEach, expect, it } from "vitest"; -import { DEFAULT_CMAKE_PROFILE } from "@/platform/cmakeSettings"; +import { afterEach, expect, it, vi } from "vitest"; +import { DEFAULT_CMAKE_PROFILE, type CMakeProfileValid } from "@/platform/cmakeSettings"; import { parseArgs } from "@/platform/commandLine"; import { PageContext } from "../components/context"; import { validateSettings } from "../model/schema"; import { useSettingsDialog } from "../model/staging"; -import { CMakeProfiles } from "../pages/cmake"; +import { cacheOverride, CMakeProfiles, withCacheValue } from "../pages/cmake"; + +const cache = vi.hoisted(() => ({ entries: [] as object[] })); +const presets = vi.hoisted(() => ({ result: { status: "ok", data: { profiles: [], presetsError: null } } as object })); +const presetProfiles = (names: string[]) => ({ + status: "ok", + data: { + profiles: names.map((name) => ({ + name, + buildType: "Debug", + generator: "Ninja", + cmakeArgs: [], + buildDir: `out/${name}`, + buildArgs: [], + env: { FROM: name }, + enabled: false, + toolchain: "", + preset: { configure: name }, + })), + presetsError: null, + }, +}); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + commands: { + ...real.commands, + cmakeProfiles: vi.fn(async () => presets.result), + cmakeCache: vi.fn(async () => ({ status: "ok", data: cache.entries })), + }, + }; +}); const savedDialog = useSettingsDialog.getState(); +const profileActions = () => within(screen.getByRole("toolbar", { name: "CMake profile actions" })); const CMAKE_CONTEXT = { pageId: "build.cmake", scope: "project" } as const; afterEach(() => { cleanup(); + presets.result = { status: "ok", data: { profiles: [], presetsError: null } }; + cache.entries = []; useSettingsDialog.setState(savedDialog, true); }); it.each([ - ["CMake arguments", "cmakeArgs"], - ["Build arguments", "buildArgs"], + ["CMake options", "cmakeArgs"], + ["Build options", "buildArgs"], ] as const)("round-trips spaces, quotes and empty values in %s", async (label, key) => { const args = ["two words", 'a "quote"', "it's", "", String.raw`C:\some path\file`]; useSettingsDialog.setState({ @@ -65,9 +100,155 @@ it("displays each profile's arguments when switching profiles", () => { , ); - fireEvent.change(screen.getByLabelText("CMake arguments"), { target: { value: '"unfinished ' } }); + fireEvent.change(screen.getByLabelText("CMake options"), { target: { value: '"unfinished ' } }); fireEvent.click(screen.getByRole("option", { name: "Release" })); - expect(parseArgs(screen.getByLabelText("CMake arguments").value)).toEqual([ + expect(parseArgs(screen.getByLabelText("CMake options").value)).toEqual([ "-DMESSAGE=release build", ]); }); + +it("lists presets with the profiles, read-only, enabled one by one and copied to edit", async () => { + presets.result = presetProfiles(["dev", "release"]); + useSettingsDialog.setState({ + base: validateSettings({ cmake: { profiles: [DEFAULT_CMAKE_PROFILE], enabledPresets: ["dev"] } }), + staged: {}, + }); + render( + + + , + ); + await screen.findByRole("option", { name: /^release/ }); + expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["Debug", "devpreset", "releasepreset"]); + // Presets are disabled until enabled, as in CLion. + fireEvent.click(screen.getByRole("option", { name: /^release/ })); + const enable = screen.getByRole("checkbox", { name: "Enable profile" }); + expect(enable).not.toBeChecked(); + expect(screen.getByLabelText("Build directory")).toHaveAttribute("readonly"); + expect(profileActions().getByRole("button", { name: "Remove" })).toBeDisabled(); + await userEvent.click(enable); + expect(useSettingsDialog.getState().staged["project|cmake.enabledPresets"]?.value).toEqual(["dev", "release"]); + // A copy is a profile of one's own, editable. + fireEvent.keyDown(screen.getByRole("listbox", { name: "CMake profiles" }), { key: "d", ctrlKey: true }); + const copied = useSettingsDialog.getState().staged["project|cmake.profiles"]?.value as CMakeProfileValid[]; + expect(copied.map((p) => p.name)).toEqual(["Debug", "release-copy"]); + expect(copied[1]).toMatchObject({ buildDir: "out/release", generator: "Ninja", env: { FROM: "release" } }); + expect(screen.getByLabelText("Build directory")).not.toHaveAttribute("readonly"); + await userEvent.click(screen.getByRole("switch", { name: "Use CMakePresets.json" })); + expect(useSettingsDialog.getState().staged["project|cmake.ignorePresets"]?.value).toBe(true); + expect(screen.queryByRole("option", { name: /^dev/ })).toBeNull(); +}); + +it("disables, moves and removes saved profiles", async () => { + const profile = (name: string) => ({ ...DEFAULT_CMAKE_PROFILE, name }); + useSettingsDialog.setState({ + base: validateSettings({ cmake: { profiles: [profile("A"), profile("B")] } }), + staged: {}, + }); + render( + + + , + ); + const staged = () => useSettingsDialog.getState().staged["project|cmake.profiles"]?.value as CMakeProfileValid[]; + await userEvent.click(screen.getByRole("checkbox", { name: "Enable profile" })); + expect(staged()[0]!.enabled).toBe(false); + fireEvent.click(profileActions().getByRole("button", { name: "Move Down" })); + expect(staged().map((p) => p.name)).toEqual(["B", "A"]); + fireEvent.click(profileActions().getByRole("button", { name: "Remove" })); + expect(staged().map((p) => p.name)).toEqual(["B"]); +}); + +it("shows why the presets file cannot be used", async () => { + presets.result = { status: "ok", data: { profiles: [], presetsError: "duplicate preset 'dev'" } }; + useSettingsDialog.setState({ base: validateSettings({}), staged: {} }); + render( + + + , + ); + expect(await screen.findByText("duplicate preset 'dev'")).toBeInTheDocument(); +}); + +it("says the default profile is not used until it is saved", () => { + useSettingsDialog.setState({ base: validateSettings({}), staged: {} }); + const view = render( + + + , + ); + expect(screen.getByText(/Not saved yet/)).toBeInTheDocument(); + view.unmount(); + useSettingsDialog.setState({ base: validateSettings({ cmake: { profiles: [DEFAULT_CMAKE_PROFILE] } }), staged: {} }); + render( + + + , + ); + expect(screen.queryByText(/Not saved yet/)).toBeNull(); +}); + +it("hides the presets of a remote server that predates them", async () => { + presets.result = { + status: "error", + error: { kind: "protocol", message: "command cmake_profiles is not available remotely", data: null }, + }; + useSettingsDialog.setState({ base: validateSettings({}), staged: {} }); + render( + + + , + ); + await act(async () => {}); + expect(screen.queryByText(/not available remotely/)).toBeNull(); + expect(screen.queryByRole("switch", { name: "Use CMakePresets.json" })).toBeNull(); +}); + +it("edits cache variables through the profile's CMake options, as CLion", async () => { + const entry = (name: string, kind: string, value: string, advanced = false) => ({ + name, + kind, + value, + help: "", + advanced, + }); + cache.entries = [ + entry("CMAKE_BUILD_TYPE", "STRING", "Debug"), + entry("BUILD_TESTS", "BOOL", "ON"), + entry("CMAKE_AR", "FILEPATH", "/usr/bin/ar", true), + ]; + useSettingsDialog.setState({ + base: validateSettings({ cmake: { profiles: [{ ...DEFAULT_CMAKE_PROFILE, cmakeArgs: ["-DMINE=1"] }] } }), + staged: {}, + }); + render( + + + , + ); + const table = await screen.findByRole("table", { name: "Cache variables" }); + // Advanced variables are hidden until asked for; set-but-unknown ones are listed too. + expect(within(table).queryByText("CMAKE_AR")).toBeNull(); + expect(within(table).getByText("MINE")).toBeInTheDocument(); + await userEvent.click(screen.getByRole("checkbox", { name: "Show advanced" })); + expect(within(table).getByText("CMAKE_AR")).toBeInTheDocument(); + const args = () => { + const staged = useSettingsDialog.getState().staged["project|cmake.profiles"]; + return (staged!.value as CMakeProfileValid[])[0]!.cmakeArgs; + }; + fireEvent.change(within(table).getByLabelText("CMAKE_BUILD_TYPE"), { target: { value: "Release" } }); + expect(args()).toEqual(["-DMINE=1", "-DCMAKE_BUILD_TYPE:STRING=Release"]); + await userEvent.click(within(table).getByRole("checkbox", { name: "BUILD_TESTS" })); + expect(args()).toContain("-DBUILD_TESTS:BOOL=OFF"); + fireEvent.click(within(table).getAllByRole("button", { name: "Revert" })[0]!); + expect(args()).not.toContain("-DCMAKE_BUILD_TYPE:STRING=Release"); +}); + +it("reads and rewrites -D options", () => { + expect(cacheOverride("-DNAME=a=b")).toEqual({ name: "NAME", value: "a=b" }); + expect(cacheOverride("-DNAME:BOOL=ON")).toEqual({ name: "NAME", value: "ON" }); + expect(cacheOverride("-G")).toBeNull(); + const entry = { name: "NAME", kind: "STRING" }; + expect(withCacheValue(["-DNAME=old", "-DOTHER=1"], entry, "new")).toEqual(["-DOTHER=1", "-DNAME:STRING=new"]); + expect(withCacheValue(["-DNAME:STRING=old"], entry, null)).toEqual([]); +}); diff --git a/src/features/settings/__tests__/dialog.test.tsx b/src/features/settings/__tests__/dialog.test.tsx index c6d3ea43c..b4a016919 100644 --- a/src/features/settings/__tests__/dialog.test.tsx +++ b/src/features/settings/__tests__/dialog.test.tsx @@ -154,7 +154,7 @@ describe("Settings dialog", () => { fireEvent.change(within(dialog).getByLabelText("Name"), { target: { value: "Release" } }); fireEvent.change(within(dialog).getByLabelText("Build type"), { target: { value: "Release" } }); fireEvent.change(within(dialog).getByLabelText("Generator"), { target: { value: "Ninja" } }); - fireEvent.change(within(dialog).getByLabelText("Build arguments"), { target: { value: "-j 8" } }); + fireEvent.change(within(dialog).getByLabelText("Build options"), { target: { value: "-j 8" } }); expect(settingsSet).not.toHaveBeenCalled(); await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" }))); const write = settingsSet.mock.calls.find((c) => c[1] === "cmake.profiles")!; @@ -213,7 +213,8 @@ describe("Settings dialog", () => { it("finds the Maven toolchains setting", async () => { useProject.setState({ project: { root: "/project" } as never }); const dialog = await openDialog("build.maven"); - fireEvent.change(within(dialog).getByLabelText("Search settings"), { target: { value: "Toolchains" } }); + // "Toolchains" alone names the Build › Toolchains page. + fireEvent.change(within(dialog).getByLabelText("Search settings"), { target: { value: "Toolchains file" } }); expect(within(dialog).getByLabelText("Toolchains file")).toBeInTheDocument(); }); diff --git a/src/features/settings/__tests__/toolchains.test.tsx b/src/features/settings/__tests__/toolchains.test.tsx new file mode 100644 index 000000000..eeba65d2b --- /dev/null +++ b/src/features/settings/__tests__/toolchains.test.tsx @@ -0,0 +1,86 @@ +import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { DEFAULT_TOOLCHAIN, type ToolchainValid } from "@/platform/cmakeSettings"; +import { commands } from "@/platform/ipc"; +import { PageContext } from "../components/context"; +import { validateSettings } from "../model/schema"; +import { useSettingsDialog } from "../model/staging"; +import { Toolchains } from "../pages/toolchains"; + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + commands: { + ...real.commands, + toolchainCheck: vi.fn(async () => ({ + status: "ok", + data: { + cmake: { path: "/usr/bin/cmake", version: "cmake version 3.30.0", problem: null }, + debugger: { path: null, version: null, problem: "Not found" }, + }, + })), + toolchainsDetect: vi.fn(async () => ({ + status: "ok", + data: [{ name: "MSYS2 ucrt64", kind: "mingw", path: "C:\\msys64\\ucrt64" }], + })), + }, + }; +}); + +const savedDialog = useSettingsDialog.getState(); +const CONTEXT = { pageId: "build.toolchains", scope: "global" } as const; +const actions = () => within(screen.getByRole("toolbar", { name: "Toolchain actions" })); +const staged = () => useSettingsDialog.getState().staged["global|toolchains"]?.value as ToolchainValid[]; +afterEach(() => { + cleanup(); + vi.useRealTimers(); + useSettingsDialog.setState(savedDialog, true); +}); + +function mount(toolchains: unknown[] = []) { + useSettingsDialog.setState({ globalBase: validateSettings({ toolchains }), base: validateSettings({}), staged: {} }); + render( + + + , + ); +} + +it("shows the default System toolchain until one is saved, then adds MinGW installs once", async () => { + vi.useFakeTimers(); + mount(); + expect(screen.getByRole("option", { name: /Default/ })).toHaveTextContent("default"); + expect(screen.getByText(/Not saved yet/)).toBeInTheDocument(); + expect(actions().getByRole("button", { name: "Remove" })).toBeDisabled(); + await act(async () => vi.advanceTimersByTimeAsync(500)); + // CLion's placeholder names what an empty field resolves to. + expect(screen.getByLabelText("CMake")).toHaveAttribute("placeholder", "Detected: cmake"); + expect(screen.getByLabelText("Debugger")).toHaveAttribute("placeholder", "Detect"); + vi.useRealTimers(); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Detect MinGW" }))); + expect(staged()).toEqual([ + DEFAULT_TOOLCHAIN, + { ...DEFAULT_TOOLCHAIN, name: "MSYS2 ucrt64", kind: "mingw", path: "C:\\msys64\\ucrt64" }, + ]); + expect(screen.getByLabelText("Toolset")).toHaveValue("C:\\msys64\\ucrt64"); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Detect MinGW" }))); + expect(staged()).toHaveLength(2); +}); + +it("edits, copies, orders and checks toolchains", async () => { + vi.useFakeTimers(); + mount([{ ...DEFAULT_TOOLCHAIN, name: "System" }]); + fireEvent.change(screen.getByLabelText("CMake"), { target: { value: "/opt/cmake/bin/cmake" } }); + expect(staged()[0]!.cmake).toBe("/opt/cmake/bin/cmake"); + await act(async () => vi.advanceTimersByTimeAsync(500)); + expect(commands.toolchainCheck).toHaveBeenCalledWith(expect.objectContaining({ cmake: "/opt/cmake/bin/cmake" })); + expect(screen.getByText(/cmake version 3\.30\.0/)).toBeInTheDocument(); + expect(screen.getByText("Not found")).toBeInTheDocument(); + fireEvent.click(actions().getByRole("button", { name: "Copy" })); + expect(staged().map((t) => t.name)).toEqual(["System", "System 2"]); + fireEvent.click(actions().getByRole("button", { name: "Move Up" })); + expect(staged().map((t) => t.name)).toEqual(["System 2", "System"]); + fireEvent.click(actions().getByRole("button", { name: "Remove" })); + expect(staged().map((t) => t.name)).toEqual(["System"]); +}); diff --git a/src/features/settings/model/schema.ts b/src/features/settings/model/schema.ts index 9dc99397a..d69a53e79 100644 --- a/src/features/settings/model/schema.ts +++ b/src/features/settings/model/schema.ts @@ -6,7 +6,7 @@ */ import { DEFAULT_FILE_COLORS, validateFileColors, type FileColorSettings } from "@/platform/fileColors"; import { validateScopes, type NamedScope } from "@/platform/scopes"; -import { validateCMake } from "@/platform/cmakeSettings"; +import { validateCMake, validateToolchains, type ToolchainValid } from "@/platform/cmakeSettings"; import { SUPPORTED_LOCALES, type Locale } from "@/platform/i18n"; import { DEFAULT_IGNORED_NAMES } from "@/platform/ignoredNames"; import { validateFileTypeOverrides, validateFileTypes, type FileTypeAssociations } from "@/platform/fileTypes"; @@ -150,6 +150,8 @@ export interface ValidSettings extends WorkflowSettings { settingsSync: SettingsSyncValid; languages: LanguagesValid; cmake: ReturnType; + /** Build, Execution, Deployment › Toolchains (global); the first is the default. */ + toolchains: ToolchainValid[]; projectStructure: ProjectStructureValid; inspections: InspectionSettingsValid; /** Editor › Natural Languages › Spelling. */ @@ -275,6 +277,7 @@ export const DEFAULT_SETTINGS: ValidSettings = { settingsSync: DEFAULT_SETTINGS_SYNC, languages: DEFAULT_LANGUAGES, cmake: {}, + toolchains: [], projectStructure: DEFAULT_PROJECT_STRUCTURE, inspections: DEFAULT_INSPECTIONS, spelling: { ideWords: [], projectWords: [], customDictionaries: [], defaultDictionary: "" }, @@ -580,6 +583,7 @@ export function validateSettings(raw: Settings | unknown): ValidSettings { ) as SettingsSyncValid, languages: validateLanguages(root.languages), cmake: validateCMake(root.cmake), + toolchains: validateToolchains(root.toolchains), projectStructure: validateProjectStructure(root.projectStructure), inspections: validateInspections(root.inspections), spelling: validateSpelling(root.spelling), diff --git a/src/features/settings/pages/CMake.module.css b/src/features/settings/pages/CMake.module.css index 1196d4e8f..cd77a94d2 100644 --- a/src/features/settings/pages/CMake.module.css +++ b/src/features/settings/pages/CMake.module.css @@ -2,3 +2,38 @@ width: 100%; text-align: left; } + +/* CLion greys out the profiles that are not enabled. */ +.disabled { + color: var(--fg-subtle); +} + +.badge { + margin-left: 6px; + padding: 0 4px; + border-radius: 3px; + font-size: var(--fs-small); + color: var(--fg-subtle); + border: 1px solid var(--border); +} + +.cache { + border-collapse: collapse; + width: 100%; +} + +.cache td { + padding: 2px 6px 2px 0; + vertical-align: middle; +} + +.cacheName { + font-family: var(--font-mono); + font-size: var(--fs-small); + white-space: nowrap; +} + +/* CLion shows the values the profile sets in bold. */ +.overridden .cacheName { + font-weight: 600; +} diff --git a/src/features/settings/pages/cmake.tsx b/src/features/settings/pages/cmake.tsx index 05c15fbbd..92db00ae9 100644 --- a/src/features/settings/pages/cmake.tsx +++ b/src/features/settings/pages/cmake.tsx @@ -1,21 +1,34 @@ -import { useId, useState } from "react"; -import { DEFAULT_CMAKE_PROFILE, type CMakeProfileValid } from "@/platform/cmakeSettings"; +import { useEffect, useId, useState, type KeyboardEvent } from "react"; +import type { CacheEntry, CMakeProfile_Serialize as ListedProfile } from "@/bindings"; +import { DEFAULT_CMAKE_PROFILE, type CMakeProfileValid, type ToolchainValid } from "@/platform/cmakeSettings"; import { formatArgs, parseArgs } from "@/platform/commandLine"; import { tx } from "@/platform/i18n"; -import { IconButton, Input, T } from "@/ui"; +import { call, commands, IpcError } from "@/platform/ipc"; +import { Checkbox, IconButton, Input, Select, T, Toggle } from "@/ui"; import { Row, Section } from "../components/Form"; import { useSetting } from "../components/context"; import { TableEditor } from "./workflowControls"; import styles from "./Workflow.module.css"; import own from "./CMake.module.css"; -function ArgumentsInput({ id, value, onChange }: { id: string; value: string[]; onChange: (args: string[]) => void }) { +function ArgumentsInput({ + id, + value, + onChange, + readOnly, +}: { + id: string; + value: string[]; + onChange: (args: string[]) => void; + readOnly?: boolean; +}) { const [text, setText] = useState(); return ( { setText(e.target.value); onChange(parseArgs(e.target.value)); @@ -25,22 +38,225 @@ function ArgumentsInput({ id, value, onChange }: { id: string; value: string[]; ); } +/** CLion's default build directory: `cmake-build-`, `cmake-build-default` without one. */ +export function defaultBuildDir(buildType: string): string { + return "cmake-build-" + (buildType ? buildType.toLowerCase() : "default"); +} + +/** The project's presets as profiles (read-only), and why they cannot be read, if they cannot. */ +function usePresets(): { presets: ListedProfile[]; error: string | null } { + const [state, setState] = useState<{ presets: ListedProfile[]; error: string | null }>({ presets: [], error: null }); + useEffect(() => { + let live = true; + call(commands.cmakeProfiles()) + .then(({ profiles, presetsError }) => { + if (!live) return; + const presets = (profiles as ListedProfile[]).filter((p) => p.preset); + setState({ presets, error: presetsError }); + }) + .catch((e: unknown) => { + if (!live) return; + // A remote server older than this app has no presets support at all: nothing to show. + const older = + e instanceof IpcError && + e.kind === "protocol" && + e.message === "command cmake_profiles is not available remotely"; + setState({ presets: [], error: older ? null : e instanceof Error ? e.message : String(e) }); + }); + return () => { + live = false; + }; + }, []); + return state; +} + +/** `-DNAME=value` / `-DNAME:TYPE=value` among CMake options: the cache variable it sets. */ +export function cacheOverride(arg: string): { name: string; value: string } | null { + const match = /^-D([^=:]+)(?::[^=]*)?=(.*)$/s.exec(arg); + return match ? { name: match[1]!, value: match[2]! } : null; +} + +/** CMake options with `name` set to `value` (replacing an earlier -D of it), or without it (`null`). */ +export function withCacheValue(args: string[], entry: Pick, value: string | null) { + const rest = args.filter((a) => cacheOverride(a)?.name !== entry.name); + return value === null ? rest : [...rest, `-D${entry.name}${entry.kind ? `:${entry.kind}` : ""}=${value}`]; +} + +/** CLion's Cache variables: the build directory's `CMakeCache.txt`, edited through CMake options. */ +function CacheVariables({ + buildDir, + cmakeArgs, + readOnly, + onChange, +}: { + buildDir: string; + cmakeArgs: string[]; + readOnly: boolean; + onChange: (args: string[]) => void; +}) { + const [entries, setEntries] = useState(null); + const [advanced, setAdvanced] = useState(false); + useEffect(() => { + let live = true; + call(commands.cmakeCache(buildDir)) + .then((list) => live && setEntries(list)) + .catch(() => live && setEntries([])); + return () => { + live = false; + }; + }, [buildDir]); + const overrides = new Map( + cmakeArgs.flatMap((a) => { + const o = cacheOverride(a); + return o ? [[o.name, o.value] as const] : []; + }), + ); + if (entries === null) return null; + // Variables set by the options but not in the cache yet are shown too (in bold, as user-defined). + const known = new Set(entries.map((e) => e.name)); + const rows: CacheEntry[] = [ + ...entries.filter((e) => advanced || !e.advanced || overrides.has(e.name)), + ...[...overrides.keys()] + .filter((name) => !known.has(name)) + .map((name) => ({ name, kind: "", value: "", help: "", advanced: false })), + ]; + return ( + + {entries.length === 0 ? ( +
+ No CMakeCache.txt yet: the variables show once the profile is configured. +
+ ) : ( + + )} + {rows.length > 0 && ( + + + {rows.map((entry) => { + const overridden = overrides.get(entry.name); + const value = overridden ?? entry.value; + const set = (next: string | null) => onChange(withCacheValue(cmakeArgs, entry, next)); + return ( + + + + + + ); + })} + +
{entry.name} + {entry.kind === "BOOL" ? ( + set(on ? "ON" : "OFF")} + /> + ) : ( + set(e.target.value)} + /> + )} + + {overridden !== undefined && !readOnly && ( + set(null)} /> + )} +
+ )} +
+ ); +} + +/** A copy of `profile` the user can edit: a saved profile with the next free name. */ +function copyOf(profile: CMakeProfileValid | ListedProfile, taken: string[]): CMakeProfileValid { + let name = `${profile.name}-copy`; + for (let n = 2; taken.includes(name); n++) name = `${profile.name}-copy${n}`; + return { + name, + buildType: profile.buildType, + generator: profile.generator, + cmakeArgs: [...profile.cmakeArgs], + buildDir: profile.buildDir, + buildArgs: [...profile.buildArgs], + env: { ...profile.env }, + enabled: true, + toolchain: profile.toolchain, + }; +} + +/** Settings › Build, Execution, Deployment › CMake, laid out as CLion's: the saved profiles and the + * presets in one list, each enabled or not, presets read-only until copied. */ export function CMakeProfiles() { const [saved, setProfiles] = useSetting("cmake.profiles"); + const [enabledPresets, setEnabledPresets] = useSetting("cmake.enabledPresets"); + const [ignore, setIgnore] = useSetting("cmake.ignorePresets"); + const [toolchains] = useSetting("toolchains", "global"); + const { presets, error } = usePresets(); const profiles = saved ?? [DEFAULT_CMAKE_PROFILE]; + const shownPresets = ignore ? [] : presets; + const total = profiles.length + shownPresets.length; const [selected, setSelected] = useState(0); - const index = Math.min(selected, Math.max(0, profiles.length - 1)); - const current = profiles[index]; + const index = Math.min(selected, Math.max(0, total - 1)); + const preset: ListedProfile | undefined = + index >= profiles.length ? shownPresets[index - profiles.length] : undefined; + const current: CMakeProfileValid | ListedProfile | undefined = preset ?? profiles[index]; + const presetName = preset?.preset?.configure; + const on = enabledPresets ?? []; + const enabled = (i: number) => + i < profiles.length + ? profiles[i]!.enabled !== false + : on.includes(shownPresets[i - profiles.length]?.preset?.configure ?? ""); const id = useId(); const update = (patch: Partial) => setProfiles(profiles.map((p, i) => (i === index ? { ...p, ...patch } : p))); + const names = [...profiles.map((p) => p.name), ...shownPresets.map((p) => p.name)]; + const copy = () => { + if (!current) return; + setProfiles([...profiles, copyOf(current, names)]); + setSelected(profiles.length); + }; + const move = (by: -1 | 1) => { + const to = index + by; + if (preset || to < 0 || to >= profiles.length) return; + const next = [...profiles]; + [next[index], next[to]] = [next[to]!, next[index]!]; + setProfiles(next); + setSelected(to); + }; + const setEnabled = (value: boolean) => { + if (presetName) setEnabledPresets(value ? [...on, presetName] : on.filter((n) => n !== presetName)); + else update({ enabled: value }); + }; + const onListKey = (e: KeyboardEvent) => { + if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "d") { + e.preventDefault(); + copy(); + } else if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + setSelected(Math.max(0, Math.min(total - 1, index + (e.key === "ArrowDown" ? 1 : -1)))); + } + }; + const toolchainNames = (toolchains ?? []).map((t) => t.name); + const toolchainOptions = [ + { value: "", label: tx("Use Default") }, + ...toolchainNames.map((name) => ({ value: name, label: name, verbatim: true })), + ...(current?.toolchain && !toolchainNames.includes(current.toolchain) + ? [{ value: current.toolchain, label: tx`${current.toolchain} (not found)` }] + : []), + ]; + const readOnly = !!preset; const fields = [ ["name", "Name"], ["buildType", "Build type"], ["generator", "Generator"], - ["cmakeArgs", "CMake arguments"], + ["cmakeArgs", "CMake options"], ["buildDir", "Build directory"], - ["buildArgs", "Build arguments"], + ["buildArgs", "Build options"], ] as const; return (
@@ -52,10 +268,8 @@ export function CMakeProfiles() { title="Add" size="small" onClick={() => { - setProfiles([ - ...profiles, - { ...DEFAULT_CMAKE_PROFILE, name: tx`CMake profile ${profiles.length + 1}`, env: {} }, - ]); + const next = profiles.length + 1; + setProfiles([...profiles, { ...DEFAULT_CMAKE_PROFILE, name: tx`CMake profile ${next}`, env: {} }]); setSelected(profiles.length); }} /> @@ -63,40 +277,106 @@ export function CMakeProfiles() { icon="minus" title="Remove" size="small" - disabled={!current} + disabled={!current || readOnly} onClick={() => { setProfiles(profiles.filter((_, i) => i !== index)); setSelected(Math.max(0, index - 1)); }} /> + + move(-1)} + /> + = profiles.length - 1} + onClick={() => move(1)} + />
-
- {profiles.map((p, i) => ( +
+ {[...profiles, ...shownPresets].map((p, i) => ( ))} - {profiles.length === 0 && No CMake profiles. Click + to add one.} + {total === 0 && No CMake profiles. Click + to add one.}
+ {saved === undefined && ( +
+ + Not saved yet: until a profile is edited or added, the build directories already configured in the project + (else build/) are used. + +
+ )} {current && (
- {fields.map(([key, label]) => ( + + {readOnly && ( +
+ From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own. +
+ )} + {fields.slice(0, 2).map(([key, label]) => ( + + update({ [key]: e.target.value })} + /> + + ))} + + update({ name: e.target.value })} + /> + + + update({ path: e.target.value })} + /> + + )} + {TOOLS.map(([key, label]) => ( + +
+ update({ [key]: e.target.value })} + /> + {check && } +
+
+ ))} +
+ + Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are + passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM. + +
+
+ )} +
+ ); +} diff --git a/src/platform/cmakeSettings.ts b/src/platform/cmakeSettings.ts index 6c4cd5edf..c1ca7478a 100644 --- a/src/platform/cmakeSettings.ts +++ b/src/platform/cmakeSettings.ts @@ -1,6 +1,48 @@ -import type { CMakeProfile } from "@/bindings"; +import type { CMakeProfile, Toolchain, ToolchainKind } from "@/bindings"; -export type CMakeProfileValid = Required; +/** A profile as saved in the settings; `preset` only exists on the profiles made from presets. */ +export type CMakeProfileValid = Required>; + +export interface CMakeValid { + profiles?: CMakeProfileValid[]; + ignorePresets?: boolean; + /** Presets are listed disabled until named here, as in CLion. */ + enabledPresets?: string[]; + /** The profile the toolbar switcher picked; empty = the first enabled one. */ + activeProfile?: string; +} + +export type ToolchainValid = Required; + +export const DEFAULT_TOOLCHAIN: ToolchainValid = { + name: "Default", + kind: "system", + path: "", + cmake: "", + buildTool: "", + cCompiler: "", + cxxCompiler: "", + debugger: "", +}; + +const TOOLCHAIN_KINDS: ToolchainKind[] = ["system", "mingw"]; + +export function validateToolchains(raw: unknown): ToolchainValid[] { + if (!Array.isArray(raw)) return []; + const string = (value: unknown) => (typeof value === "string" ? value : ""); + return raw + .filter((t) => t && typeof t === "object") + .map((t) => ({ + name: string(t.name), + kind: TOOLCHAIN_KINDS.includes(t.kind) ? t.kind : "system", + path: string(t.path), + cmake: string(t.cmake), + buildTool: string(t.buildTool), + cCompiler: string(t.cCompiler), + cxxCompiler: string(t.cxxCompiler), + debugger: string(t.debugger), + })); +} export const DEFAULT_CMAKE_PROFILE: CMakeProfileValid = { name: "Debug", @@ -10,15 +52,30 @@ export const DEFAULT_CMAKE_PROFILE: CMakeProfileValid = { buildDir: "", buildArgs: [], env: {}, + enabled: true, + toolchain: "", }; -export function validateCMake(raw: unknown): { profiles?: CMakeProfileValid[] } { - const profiles = (raw as { profiles?: unknown } | undefined)?.profiles; - if (!Array.isArray(profiles)) return {}; +export function validateCMake(raw: unknown): CMakeValid { + const cmake = (raw ?? {}) as { + profiles?: unknown; + ignorePresets?: unknown; + enabledPresets?: unknown; + activeProfile?: unknown; + }; + const presets: CMakeValid = {}; + if (typeof cmake.ignorePresets === "boolean") presets.ignorePresets = cmake.ignorePresets; + if (Array.isArray(cmake.enabledPresets)) { + presets.enabledPresets = cmake.enabledPresets.filter((name): name is string => typeof name === "string"); + } + if (typeof cmake.activeProfile === "string") presets.activeProfile = cmake.activeProfile; + const profiles = cmake.profiles; + if (!Array.isArray(profiles)) return presets; const string = (value: unknown, fallback = "") => (typeof value === "string" ? value : fallback); const args = (value: unknown): string[] => Array.isArray(value) ? value.filter((arg): arg is string => typeof arg === "string") : []; return { + ...presets, profiles: profiles .filter((p) => p && typeof p === "object") .map((p) => ({ @@ -28,6 +85,8 @@ export function validateCMake(raw: unknown): { profiles?: CMakeProfileValid[] } cmakeArgs: args(p.cmakeArgs), buildDir: string(p.buildDir), buildArgs: args(p.buildArgs), + enabled: p.enabled !== false, + toolchain: string(p.toolchain), env: Object.fromEntries( Object.entries(p.env && typeof p.env === "object" ? p.env : {}).filter( (entry): entry is [string, string] => typeof entry[1] === "string", diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 97aea1059..fd5b55918 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -5573,14 +5573,14 @@ "CMake profiles": "Perfiles de CMake", "CMake profile actions": "Acciones del perfil de CMake", "No CMake profiles. Click + to add one.": "No hay perfiles de CMake. Haga clic en + para agregar uno.", + "CMake presets": "Presets de CMake", + "Use CMakePresets.json": "Usar CMakePresets.json", + "Not saved yet: until a profile is edited or added, the build directories already configured in the project (else build/) are used.": "Aún no guardado: hasta que se edite o agregue un perfil, se usan los directorios de compilación ya configurados en el proyecto (si no, build/).", "Profile settings": "Configuración del perfil", "Build type": "Tipo de compilación", "Generator": "Generador", "CMake arguments": "Argumentos de CMake", "Build directory": "Directorio de compilación", - "Build arguments": "Argumentos de compilación", - "CMake default": "Predeterminado de CMake", - "Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "Ponga entre comillas los argumentos que contengan espacios. Los argumentos de compilación van a cmake --build; use -- antes de las opciones de la herramienta de compilación nativa.", "CMake profile {0}": "Perfil de CMake {0}", ".NET Project": "Proyecto .NET", ".NET project": "Proyecto .NET", @@ -6238,6 +6238,33 @@ "Library name": "Nombre de biblioteca", "Library name cannot be empty.": "El nombre de la biblioteca no puede estar vacío.", "A library with this name already exists.": "Ya existe una biblioteca con este nombre.", + "CMake Profile": "Perfil de CMake", + "CMake profile: {active}": "Perfil de CMake: {active}", + "Select CMake Profile…": "Seleccionar perfil de CMake…", + "Use CMake Profile": "Usar perfil de CMake", + "Cannot select the CMake profile": "No se puede seleccionar el perfil de CMake", + "CMake Settings…": "Configuración de CMake…", + "Use Default": "Usar el predeterminado", + "preset": "preset", + "Enable profile": "Habilitar perfil", + "From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own.": "De CMakePresets.json: solo lectura. Cópielo (Ctrl+D) para editar un perfil propio.", + "Let CMake decide": "Dejar que CMake decida", + "Quote arguments containing spaces. Build options go to cmake --build; use -- before native build tool options.": "Ponga entre comillas los argumentos con espacios. Las opciones de compilación van a cmake --build; use -- antes de las opciones de la herramienta de compilación nativa.", + "Presets are listed with the profiles, disabled until enabled.": "Los presets aparecen con los perfiles, deshabilitados hasta que se habiliten.", + "Toolchains": "Cadenas de herramientas", + "Toolchain actions": "Acciones de cadena de herramientas", + "Detect MinGW": "Detectar MinGW", + "The first toolchain is the default one; a CMake profile can choose another.": "La primera cadena de herramientas es la predeterminada; un perfil de CMake puede elegir otra.", + "Toolchain settings": "Configuración de la cadena de herramientas", + "Toolset": "Conjunto de herramientas", + "Detect": "Detectar", + "Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "Los campos vacíos se detectan: desde el conjunto de herramientas MinGW, si no desde PATH. Los compiladores y la herramienta de compilación se pasan a CMake como CMAKE_C_COMPILER, CMAKE_CXX_COMPILER y CMAKE_MAKE_PROGRAM.", + "No answer to --version": "Sin respuesta a --version", + "Cache variables": "Variables de caché", + "No CMakeCache.txt yet: the variables show once the profile is configured.": "Aún no hay CMakeCache.txt: las variables aparecen cuando se configura el perfil.", + "Show advanced": "Mostrar avanzadas", + "Detected: {name}": "Detectado: {name}", + "Not saved yet: until a toolchain is edited or added, the tools found on PATH are used.": "Aún no guardada: hasta que se edite o añada una toolchain, se usan las herramientas encontradas en el PATH.", "Compare Value with Clipboard": "Comparar valor con el portapapeles", "Cannot compare the value": "No se puede comparar el valor", "The clipboard could not be read": "No se pudo leer el portapapeles" diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index 0d2cd0f8e..3a9f58c1b 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -5413,14 +5413,14 @@ "CMake profiles": "Profils CMake", "CMake profile actions": "Actions des profils CMake", "No CMake profiles. Click + to add one.": "Aucun profil CMake. Cliquez sur + pour en ajouter un.", + "CMake presets": "Presets CMake", + "Use CMakePresets.json": "Utiliser CMakePresets.json", + "Not saved yet: until a profile is edited or added, the build directories already configured in the project (else build/) are used.": "Pas encore enregistré : tant qu'aucun profil n'est modifié ou ajouté, les répertoires de build déjà configurés dans le projet (sinon build/) sont utilisés.", "Profile settings": "Paramètres du profil", "Build type": "Type de build", "Generator": "Générateur", "CMake arguments": "Arguments de CMake", "Build directory": "Répertoire de build", - "Build arguments": "Arguments de build", - "CMake default": "Valeur par défaut de CMake", - "Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "Mettez entre guillemets les arguments contenant des espaces. Les arguments de build sont passés à cmake --build ; utilisez -- avant les options de l'outil de build natif.", "CMake profile {0}": "Profil CMake {0}", ".NET Project": "Projet .NET", ".NET project": "Projet .NET", @@ -5883,6 +5883,33 @@ "Library name": "Nom de la bibliothèque", "Library name cannot be empty.": "Le nom de la bibliothèque ne peut pas être vide.", "A library with this name already exists.": "Une bibliothèque portant ce nom existe déjà.", + "CMake Profile": "Profil CMake", + "CMake profile: {active}": "Profil CMake : {active}", + "Select CMake Profile…": "Sélectionner le profil CMake…", + "Use CMake Profile": "Utiliser le profil CMake", + "Cannot select the CMake profile": "Impossible de sélectionner le profil CMake", + "CMake Settings…": "Paramètres CMake…", + "Use Default": "Utiliser la valeur par défaut", + "preset": "preset", + "Enable profile": "Activer le profil", + "From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own.": "Issu de CMakePresets.json : lecture seule. Copiez-le (Ctrl+D) pour modifier votre propre profil.", + "Let CMake decide": "Laisser CMake décider", + "Quote arguments containing spaces. Build options go to cmake --build; use -- before native build tool options.": "Mettez entre guillemets les arguments contenant des espaces. Les options de build vont à cmake --build ; utilisez -- avant les options de l'outil de build natif.", + "Presets are listed with the profiles, disabled until enabled.": "Les presets sont listés avec les profils, désactivés tant qu'ils ne sont pas activés.", + "Toolchains": "Toolchains", + "Toolchain actions": "Actions de toolchain", + "Detect MinGW": "Détecter MinGW", + "The first toolchain is the default one; a CMake profile can choose another.": "La première toolchain est celle par défaut ; un profil CMake peut en choisir une autre.", + "Toolchain settings": "Paramètres de la toolchain", + "Toolset": "Jeu d'outils", + "Detect": "Détecter", + "Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "Les champs vides sont détectés : depuis le jeu d'outils MinGW, sinon depuis le PATH. Les compilateurs et l'outil de build sont passés à CMake via CMAKE_C_COMPILER, CMAKE_CXX_COMPILER et CMAKE_MAKE_PROGRAM.", + "No answer to --version": "Pas de réponse à --version", + "Cache variables": "Variables du cache", + "No CMakeCache.txt yet: the variables show once the profile is configured.": "Pas encore de CMakeCache.txt : les variables s'affichent une fois le profil configuré.", + "Show advanced": "Afficher les avancées", + "Detected: {name}": "Détecté : {name}", + "Not saved yet: until a toolchain is edited or added, the tools found on PATH are used.": "Pas encore enregistrée : tant qu'aucune toolchain n'est modifiée ou ajoutée, les outils trouvés dans le PATH sont utilisés.", "Compare Value with Clipboard": "Comparer la valeur avec le presse-papiers", "Cannot compare the value": "Impossible de comparer la valeur", "The clipboard could not be read": "Impossible de lire le presse-papiers" diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 4f1f0c314..7339c42db 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -5640,14 +5640,14 @@ "CMake profiles": "CMake 프로필", "CMake profile actions": "CMake 프로필 액션", "No CMake profiles. Click + to add one.": "CMake 프로필이 없습니다. +를 클릭하여 추가하세요.", + "CMake presets": "CMake 프리셋", + "Use CMakePresets.json": "CMakePresets.json 사용", + "Not saved yet: until a profile is edited or added, the build directories already configured in the project (else build/) are used.": "아직 저장되지 않음: 프로필을 편집하거나 추가할 때까지 프로젝트에 이미 구성된 빌드 디렉터리(없으면 build/)가 사용됩니다.", "Profile settings": "프로필 설정", "Build type": "빌드 유형", "Generator": "생성기", "CMake arguments": "CMake 인수", "Build directory": "빌드 디렉터리", - "Build arguments": "빌드 인수", - "CMake default": "CMake 기본값", - "Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "공백이 포함된 인수는 따옴표로 묶으세요. 빌드 인수는 cmake --build에 전달됩니다. 네이티브 빌드 도구 옵션 앞에는 --를 사용하세요.", "CMake profile {0}": "CMake 프로필 {0}", ".NET Project": ".NET 프로젝트", ".NET project": ".NET 프로젝트", @@ -6348,6 +6348,33 @@ "Library name": "라이브러리 이름", "Library name cannot be empty.": "라이브러리 이름은 비워 둘 수 없습니다.", "A library with this name already exists.": "이 이름의 라이브러리가 이미 존재합니다.", + "CMake Profile": "CMake 프로필", + "CMake profile: {active}": "CMake 프로필: {active}", + "Select CMake Profile…": "CMake 프로필 선택…", + "Use CMake Profile": "CMake 프로필 사용", + "Cannot select the CMake profile": "CMake 프로필을 선택할 수 없음", + "CMake Settings…": "CMake 설정…", + "Use Default": "기본값 사용", + "preset": "프리셋", + "Enable profile": "프로필 사용", + "From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own.": "CMakePresets.json에서 가져옴: 읽기 전용입니다. 복사(Ctrl+D)하여 자신의 프로필로 편집하세요.", + "Let CMake decide": "CMake가 결정", + "Quote arguments containing spaces. Build options go to cmake --build; use -- before native build tool options.": "공백이 있는 인수는 따옴표로 묶으세요. 빌드 옵션은 cmake --build에 전달되며, 네이티브 빌드 도구 옵션 앞에는 --를 사용하세요.", + "Presets are listed with the profiles, disabled until enabled.": "프리셋은 프로필과 함께 표시되며, 사용하도록 설정하기 전까지 비활성화됩니다.", + "Toolchains": "툴체인", + "Toolchain actions": "툴체인 작업", + "Detect MinGW": "MinGW 감지", + "The first toolchain is the default one; a CMake profile can choose another.": "첫 번째 툴체인이 기본값이며, CMake 프로필에서 다른 툴체인을 선택할 수 있습니다.", + "Toolchain settings": "툴체인 설정", + "Toolset": "도구 집합", + "Detect": "감지", + "Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "빈 필드는 MinGW 도구 집합에서, 없으면 PATH에서 감지됩니다. 컴파일러와 빌드 도구는 CMAKE_C_COMPILER, CMAKE_CXX_COMPILER, CMAKE_MAKE_PROGRAM으로 CMake에 전달됩니다.", + "No answer to --version": "--version에 응답 없음", + "Cache variables": "캐시 변수", + "No CMakeCache.txt yet: the variables show once the profile is configured.": "아직 CMakeCache.txt가 없습니다. 프로필을 구성하면 변수가 표시됩니다.", + "Show advanced": "고급 표시", + "Detected: {name}": "감지됨: {name}", + "Not saved yet: until a toolchain is edited or added, the tools found on PATH are used.": "아직 저장되지 않음: 툴체인을 편집하거나 추가하기 전까지 PATH에서 찾은 도구를 사용합니다.", "Compare Value with Clipboard": "값을 클립보드와 비교", "Cannot compare the value": "값을 비교할 수 없습니다", "The clipboard could not be read": "클립보드를 읽을 수 없습니다" diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 5156a5239..36440dfe7 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -5524,14 +5524,14 @@ "CMake profiles": "Profile CMake", "CMake profile actions": "Akcje profili CMake", "No CMake profiles. Click + to add one.": "Brak profili CMake. Kliknij +, aby dodać.", + "CMake presets": "Presety CMake", + "Use CMakePresets.json": "Użyj CMakePresets.json", + "Not saved yet: until a profile is edited or added, the build directories already configured in the project (else build/) are used.": "Jeszcze nie zapisano: dopóki profil nie zostanie edytowany lub dodany, używane są katalogi kompilacji już skonfigurowane w projekcie (w przeciwnym razie build/).", "Profile settings": "Ustawienia profilu", "Build type": "Typ kompilacji", "Generator": "Generator", "CMake arguments": "Argumenty CMake", "Build directory": "Katalog kompilacji", - "Build arguments": "Argumenty budowania", - "CMake default": "Domyślne dla CMake", - "Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "Argumenty zawierające spacje umieszczaj w cudzysłowach. Argumenty budowania przekazywane są do 'cmake --build'; użyj '--' przed opcjami natywnego narzędzia budowania.", "CMake profile {0}": "Profil CMake {0}", ".NET Project": "Projekt .NET", ".NET project": "Projekt .NET", @@ -6046,6 +6046,33 @@ "Library name": "Nazwa biblioteki", "Library name cannot be empty.": "Nazwa biblioteki nie może być pusta.", "A library with this name already exists.": "Biblioteka o tej nazwie już istnieje.", + "CMake Profile": "Profil CMake", + "CMake profile: {active}": "Profil CMake: {active}", + "Select CMake Profile…": "Wybierz profil CMake…", + "Use CMake Profile": "Użyj profilu CMake", + "Cannot select the CMake profile": "Nie można wybrać profilu CMake", + "CMake Settings…": "Ustawienia CMake…", + "Use Default": "Użyj domyślnego", + "preset": "preset", + "Enable profile": "Włącz profil", + "From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own.": "Z CMakePresets.json: tylko do odczytu. Skopiuj go (Ctrl+D), aby edytować własny profil.", + "Let CMake decide": "Niech zdecyduje CMake", + "Quote arguments containing spaces. Build options go to cmake --build; use -- before native build tool options.": "Argumenty zawierające spacje ujmij w cudzysłów. Opcje kompilacji trafiają do cmake --build; przed opcjami natywnego narzędzia kompilacji użyj --.", + "Presets are listed with the profiles, disabled until enabled.": "Presety są wyświetlane razem z profilami i pozostają wyłączone, dopóki ich nie włączysz.", + "Toolchains": "Łańcuchy narzędzi", + "Toolchain actions": "Akcje łańcucha narzędzi", + "Detect MinGW": "Wykryj MinGW", + "The first toolchain is the default one; a CMake profile can choose another.": "Pierwszy łańcuch narzędzi jest domyślny; profil CMake może wybrać inny.", + "Toolchain settings": "Ustawienia łańcucha narzędzi", + "Toolset": "Zestaw narzędzi", + "Detect": "Wykryj", + "Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "Puste pola są wykrywane: z zestawu narzędzi MinGW, a w przeciwnym razie z PATH. Kompilatory i narzędzie kompilacji są przekazywane do CMake jako CMAKE_C_COMPILER, CMAKE_CXX_COMPILER i CMAKE_MAKE_PROGRAM.", + "No answer to --version": "Brak odpowiedzi na --version", + "Cache variables": "Zmienne pamięci podręcznej", + "No CMakeCache.txt yet: the variables show once the profile is configured.": "Brak jeszcze CMakeCache.txt: zmienne pojawią się po skonfigurowaniu profilu.", + "Show advanced": "Pokaż zaawansowane", + "Detected: {name}": "Wykryto: {name}", + "Not saved yet: until a toolchain is edited or added, the tools found on PATH are used.": "Jeszcze nie zapisano: dopóki toolchain nie zostanie edytowany lub dodany, używane są narzędzia znalezione w PATH.", "Compare Value with Clipboard": "Porównaj wartość ze schowkiem", "Cannot compare the value": "Nie można porównać wartości", "The clipboard could not be read": "Nie można odczytać schowka" diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index e9a234179..aefb032ec 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -5539,14 +5539,14 @@ "CMake profiles": "Perfis do CMake", "CMake profile actions": "Ações do perfil CMake", "No CMake profiles. Click + to add one.": "Nenhum perfil CMake. Clique em + para adicionar um.", + "CMake presets": "Presets do CMake", + "Use CMakePresets.json": "Usar CMakePresets.json", + "Not saved yet: until a profile is edited or added, the build directories already configured in the project (else build/) are used.": "Ainda não salvo: até que um perfil seja editado ou adicionado, são usados os diretórios de build já configurados no projeto (senão build/).", "Profile settings": "Configurações do perfil", "Build type": "Tipo de build", "Generator": "Gerador", "CMake arguments": "Argumentos do CMake", "Build directory": "Diretório de build", - "Build arguments": "Argumentos de build", - "CMake default": "Padrão do CMake", - "Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "Coloque entre aspas argumentos contendo espaços. Argumentos de build vão para cmake --build; use -- antes das opções nativas da ferramenta de build.", "CMake profile {0}": "Perfil CMake {0}", ".NET Project": "Projeto .NET", ".NET project": "Projeto .NET", @@ -6061,6 +6061,33 @@ "Library name": "Nome da biblioteca", "Library name cannot be empty.": "O nome da biblioteca não pode estar vazio.", "A library with this name already exists.": "Já existe uma biblioteca com este nome.", + "CMake Profile": "Perfil do CMake", + "CMake profile: {active}": "Perfil do CMake: {active}", + "Select CMake Profile…": "Selecionar perfil do CMake…", + "Use CMake Profile": "Usar perfil do CMake", + "Cannot select the CMake profile": "Não é possível selecionar o perfil do CMake", + "CMake Settings…": "Configurações do CMake…", + "Use Default": "Usar o padrão", + "preset": "preset", + "Enable profile": "Ativar perfil", + "From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own.": "Do CMakePresets.json: somente leitura. Copie-o (Ctrl+D) para editar um perfil próprio.", + "Let CMake decide": "Deixar o CMake decidir", + "Quote arguments containing spaces. Build options go to cmake --build; use -- before native build tool options.": "Coloque entre aspas os argumentos com espaços. As opções de build vão para cmake --build; use -- antes das opções da ferramenta de build nativa.", + "Presets are listed with the profiles, disabled until enabled.": "Os presets aparecem com os perfis, desativados até serem ativados.", + "Toolchains": "Toolchains", + "Toolchain actions": "Ações de toolchain", + "Detect MinGW": "Detectar MinGW", + "The first toolchain is the default one; a CMake profile can choose another.": "A primeira toolchain é a padrão; um perfil do CMake pode escolher outra.", + "Toolchain settings": "Configurações da toolchain", + "Toolset": "Conjunto de ferramentas", + "Detect": "Detectar", + "Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "Campos vazios são detectados: no conjunto de ferramentas MinGW, senão no PATH. Os compiladores e a ferramenta de build são passados ao CMake como CMAKE_C_COMPILER, CMAKE_CXX_COMPILER e CMAKE_MAKE_PROGRAM.", + "No answer to --version": "Sem resposta para --version", + "Cache variables": "Variáveis de cache", + "No CMakeCache.txt yet: the variables show once the profile is configured.": "Ainda não há CMakeCache.txt: as variáveis aparecem depois que o perfil for configurado.", + "Show advanced": "Mostrar avançadas", + "Detected: {name}": "Detectado: {name}", + "Not saved yet: until a toolchain is edited or added, the tools found on PATH are used.": "Ainda não salva: até que uma toolchain seja editada ou adicionada, são usadas as ferramentas encontradas no PATH.", "Compare Value with Clipboard": "Comparar valor com a área de transferência", "Cannot compare the value": "Não é possível comparar o valor", "The clipboard could not be read": "Não foi possível ler a área de transferência" diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index e0c3c2e1d..5bfe5e697 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -7144,14 +7144,14 @@ "CMake profiles": "Профили CMake", "CMake profile actions": "Действия с профилями CMake", "No CMake profiles. Click + to add one.": "Нет профилей CMake. Нажмите +, чтобы добавить профиль.", + "CMake presets": "Пресеты CMake", + "Use CMakePresets.json": "Использовать CMakePresets.json", + "Not saved yet: until a profile is edited or added, the build directories already configured in the project (else build/) are used.": "Ещё не сохранено: пока профиль не изменён или не добавлен, используются каталоги сборки, уже настроенные в проекте (иначе build/).", "Profile settings": "Настройки профиля", "Build type": "Тип сборки", "Generator": "Генератор", "CMake arguments": "Аргументы CMake", "Build directory": "Каталог сборки", - "Build arguments": "Аргументы сборки", - "CMake default": "По умолчанию для CMake", - "Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "Заключайте аргументы с пробелами в кавычки. Аргументы сборки передаются в cmake --build; используйте -- перед параметрами нативного инструмента сборки.", "CMake profile {0}": "Профиль CMake {0}", ".NET Project": "Проект .NET", ".NET project": "Проект .NET", @@ -10283,6 +10283,33 @@ "Library name": "Имя библиотеки", "Library name cannot be empty.": "Имя библиотеки не может быть пустым.", "A library with this name already exists.": "Библиотека с таким именем уже существует.", + "CMake Profile": "Профиль CMake", + "CMake profile: {active}": "Профиль CMake: {active}", + "Select CMake Profile…": "Выбрать профиль CMake…", + "Use CMake Profile": "Использовать профиль CMake", + "Cannot select the CMake profile": "Не удалось выбрать профиль CMake", + "CMake Settings…": "Настройки CMake…", + "Use Default": "Использовать по умолчанию", + "preset": "пресет", + "Enable profile": "Включить профиль", + "From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own.": "Из CMakePresets.json: только для чтения. Скопируйте его (Ctrl+D), чтобы редактировать собственный профиль.", + "Let CMake decide": "На усмотрение CMake", + "Quote arguments containing spaces. Build options go to cmake --build; use -- before native build tool options.": "Заключайте аргументы с пробелами в кавычки. Параметры сборки передаются в cmake --build; перед параметрами нативного инструмента сборки укажите --.", + "Presets are listed with the profiles, disabled until enabled.": "Пресеты показаны вместе с профилями и отключены, пока их не включить.", + "Toolchains": "Наборы инструментов", + "Toolchain actions": "Действия с наборами инструментов", + "Detect MinGW": "Найти MinGW", + "The first toolchain is the default one; a CMake profile can choose another.": "Первый набор инструментов используется по умолчанию; профиль CMake может выбрать другой.", + "Toolchain settings": "Настройки набора инструментов", + "Toolset": "Набор средств", + "Detect": "Определить", + "Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "Пустые поля определяются автоматически: из набора MinGW, иначе из PATH. Компиляторы и инструмент сборки передаются в CMake как CMAKE_C_COMPILER, CMAKE_CXX_COMPILER и CMAKE_MAKE_PROGRAM.", + "No answer to --version": "Нет ответа на --version", + "Cache variables": "Переменные кеша", + "No CMakeCache.txt yet: the variables show once the profile is configured.": "CMakeCache.txt ещё нет: переменные появятся после конфигурирования профиля.", + "Show advanced": "Показать расширенные", + "Detected: {name}": "Обнаружено: {name}", + "Not saved yet: until a toolchain is edited or added, the tools found on PATH are used.": "Ещё не сохранено: пока набор инструментов не изменён и не добавлен, используются инструменты из PATH.", "Compare Value with Clipboard": "Сравнить значение с буфером обмена", "Cannot compare the value": "Не удается сравнить значение", "The clipboard could not be read": "Не удалось прочитать буфер обмена", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 5d3c56689..1a349e1b1 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -8218,14 +8218,14 @@ "CMake profiles": "CMake profilleri", "CMake profile actions": "CMake profil eylemleri", "No CMake profiles. Click + to add one.": "CMake profili yok. Eklemek için + işaretine tıklayın.", + "CMake presets": "CMake ön ayarları", + "Use CMakePresets.json": "CMakePresets.json kullan", + "Not saved yet: until a profile is edited or added, the build directories already configured in the project (else build/) are used.": "Henüz kaydedilmedi: bir profil düzenlenene veya eklenene kadar projede zaten yapılandırılmış derleme dizinleri (yoksa build/) kullanılır.", "Profile settings": "Profil ayarları", "Build type": "Derleme türü", "Generator": "Oluşturucu", "CMake arguments": "CMake bağımsız değişkenleri", "Build directory": "Derleme dizini", - "Build arguments": "Derleme bağımsız değişkenleri", - "CMake default": "CMake varsayılanı", - "Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "Boşluk içeren bağımsız değişkenleri tırnak içine alın. Derleme bağımsız değişkenleri cmake --build komutuna gider; yerel derleme aracı seçeneklerinden önce -- kullanın.", "CMake profile {0}": "CMake profili {0}", ".NET Project": ".NET Projesi", ".NET project": ".NET projesi", @@ -8902,6 +8902,33 @@ "Library name": "Kitaplık adı", "Library name cannot be empty.": "Kitaplık adı boş olamaz.", "A library with this name already exists.": "Bu ada sahip bir kitaplık zaten var.", + "CMake Profile": "CMake profili", + "CMake profile: {active}": "CMake profili: {active}", + "Select CMake Profile…": "CMake Profilini Seç…", + "Use CMake Profile": "CMake Profilini Kullan", + "Cannot select the CMake profile": "CMake profili seçilemiyor", + "CMake Settings…": "CMake Ayarları…", + "Use Default": "Varsayılanı kullan", + "preset": "ön ayar", + "Enable profile": "Profili etkinleştir", + "From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own.": "CMakePresets.json'dan: salt okunur. Kendi profilinizi düzenlemek için kopyalayın (Ctrl+D).", + "Let CMake decide": "CMake karar versin", + "Quote arguments containing spaces. Build options go to cmake --build; use -- before native build tool options.": "Boşluk içeren bağımsız değişkenleri tırnak içine alın. Derleme seçenekleri cmake --build'e gider; yerel derleme aracı seçeneklerinden önce -- kullanın.", + "Presets are listed with the profiles, disabled until enabled.": "Ön ayarlar profillerle birlikte listelenir ve etkinleştirilene kadar devre dışıdır.", + "Toolchains": "Araç zincirleri", + "Toolchain actions": "Araç zinciri eylemleri", + "Detect MinGW": "MinGW'yi algıla", + "The first toolchain is the default one; a CMake profile can choose another.": "İlk araç zinciri varsayılandır; bir CMake profili başka birini seçebilir.", + "Toolchain settings": "Araç zinciri ayarları", + "Toolset": "Araç seti", + "Detect": "Algıla", + "Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "Boş alanlar algılanır: MinGW araç setinden, yoksa PATH'ten. Derleyiciler ve derleme aracı CMake'e CMAKE_C_COMPILER, CMAKE_CXX_COMPILER ve CMAKE_MAKE_PROGRAM olarak iletilir.", + "No answer to --version": "--version yanıt vermedi", + "Cache variables": "Önbellek değişkenleri", + "No CMakeCache.txt yet: the variables show once the profile is configured.": "Henüz CMakeCache.txt yok: değişkenler profil yapılandırıldığında görünür.", + "Show advanced": "Gelişmişleri göster", + "Detected: {name}": "Algılandı: {name}", + "Not saved yet: until a toolchain is edited or added, the tools found on PATH are used.": "Henüz kaydedilmedi: bir araç zinciri düzenlenene veya eklenene kadar PATH içinde bulunan araçlar kullanılır.", "Compare Value with Clipboard": "Değeri Panoyla Karşılaştır", "Cannot compare the value": "Değer karşılaştırılamıyor", "The clipboard could not be read": "Pano okunamadı" diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index de534c4f6..b49bdc92e 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -6708,14 +6708,14 @@ "CMake profiles": "CMake 設定", "CMake profile actions": "CMake 設定操作", "No CMake profiles. Click + to add one.": "沒有 CMake 設定。點選 + 新增。", + "CMake presets": "CMake 預設", + "Use CMakePresets.json": "使用 CMakePresets.json", + "Not saved yet: until a profile is edited or added, the build directories already configured in the project (else build/) are used.": "尚未儲存:在編輯或新增設定之前,會使用專案中已設定的建置目錄(沒有時使用 build/)。", "Profile settings": "設定設定", "Build type": "建置型別", "Generator": "產生器", "CMake arguments": "CMake 引數", "Build directory": "建置目錄", - "Build arguments": "建置引數", - "CMake default": "CMake 預設", - "Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "包含空格的引數請加引號。建置引數傳給 cmake --build;原生建置工具引數前請加 --。", "CMake profile {0}": "CMake 設定 {0}", ".NET Project": ".NET 專案", ".NET project": ".NET 專案", @@ -9581,6 +9581,33 @@ "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,{effectiveAccount} 可能沒有存取權限。請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。", "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。", "GitHub Settings": "GitHub 設定", + "CMake Profile": "CMake 設定檔", + "CMake profile: {active}": "CMake 設定檔:{active}", + "Select CMake Profile…": "選擇 CMake 設定檔…", + "Use CMake Profile": "使用 CMake 設定檔", + "Cannot select the CMake profile": "無法選擇 CMake 設定檔", + "CMake Settings…": "CMake 設定…", + "Use Default": "使用預設值", + "preset": "預設", + "Enable profile": "啟用設定檔", + "From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own.": "來自 CMakePresets.json:唯讀。複製它(Ctrl+D)即可編輯自己的設定檔。", + "Let CMake decide": "由 CMake 決定", + "Quote arguments containing spaces. Build options go to cmake --build; use -- before native build tool options.": "包含空格的參數請加引號。建置選項會傳給 cmake --build;原生建置工具的選項前請加 --。", + "Presets are listed with the profiles, disabled until enabled.": "預設會與設定檔一起列出,啟用前處於停用狀態。", + "Toolchains": "工具鏈", + "Toolchain actions": "工具鏈操作", + "Detect MinGW": "偵測 MinGW", + "The first toolchain is the default one; a CMake profile can choose another.": "第一個工具鏈為預設工具鏈;CMake 設定檔可以選擇其他工具鏈。", + "Toolchain settings": "工具鏈設定", + "Toolset": "工具集", + "Detect": "自動偵測", + "Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "空白欄位會自動偵測:先從 MinGW 工具集,再從 PATH。編譯器與建置工具會以 CMAKE_C_COMPILER、CMAKE_CXX_COMPILER 與 CMAKE_MAKE_PROGRAM 傳給 CMake。", + "No answer to --version": "--version 沒有回應", + "Cache variables": "快取變數", + "No CMakeCache.txt yet: the variables show once the profile is configured.": "尚無 CMakeCache.txt:設定檔完成組態後會顯示變數。", + "Show advanced": "顯示進階", + "Detected: {name}": "已偵測:{name}", + "Not saved yet: until a toolchain is edited or added, the tools found on PATH are used.": "尚未儲存:在編輯或新增工具鏈之前,使用 PATH 中找到的工具。", "Compare Value with Clipboard": "將值與剪貼簿比較", "Cannot compare the value": "無法比較該值", "The clipboard could not be read": "無法讀取剪貼簿", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 42814afe2..262e172cd 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -7592,14 +7592,14 @@ "CMake profiles": "CMake 配置", "CMake profile actions": "CMake 配置操作", "No CMake profiles. Click + to add one.": "没有 CMake 配置。点击 + 添加。", + "CMake presets": "CMake 预设", + "Use CMakePresets.json": "使用 CMakePresets.json", + "Not saved yet: until a profile is edited or added, the build directories already configured in the project (else build/) are used.": "尚未保存:在编辑或添加配置之前,使用项目中已配置的构建目录(没有时使用 build/)。", "Profile settings": "配置设置", "Build type": "构建类型", "Generator": "生成器", "CMake arguments": "CMake 参数", "Build directory": "构建目录", - "Build arguments": "构建参数", - "CMake default": "CMake 默认", - "Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "包含空格的参数请加引号。构建参数传给 cmake --build;原生构建工具参数前请加 --。", "CMake profile {0}": "CMake 配置 {0}", ".NET Project": ".NET 项目", ".NET project": ".NET 项目", @@ -11856,6 +11856,33 @@ "Repository {name} is unavailable": "仓库 {name} 不可用", "{count} repositories are unavailable": "{count} 个仓库不可用", "The directory {root} cannot be reached. Make sure it is accessible or update Directory Mappings.": "无法访问目录 {root}。请确保该目录可访问,或更新目录映射。", + "CMake Profile": "CMake 配置", + "CMake profile: {active}": "CMake 配置:{active}", + "Select CMake Profile…": "选择 CMake 配置…", + "Use CMake Profile": "使用 CMake 配置", + "Cannot select the CMake profile": "无法选择 CMake 配置", + "CMake Settings…": "CMake 设置…", + "Use Default": "使用默认值", + "preset": "预设", + "Enable profile": "启用配置", + "From CMakePresets.json: read-only. Copy it (Ctrl+D) to edit a profile of your own.": "来自 CMakePresets.json:只读。复制它(Ctrl+D)即可编辑自己的配置。", + "Let CMake decide": "由 CMake 决定", + "Quote arguments containing spaces. Build options go to cmake --build; use -- before native build tool options.": "包含空格的参数请加引号。构建选项传给 cmake --build;原生构建工具的选项前请加 --。", + "Presets are listed with the profiles, disabled until enabled.": "预设与配置一同列出,启用之前处于禁用状态。", + "Toolchains": "工具链", + "Toolchain actions": "工具链操作", + "Detect MinGW": "检测 MinGW", + "The first toolchain is the default one; a CMake profile can choose another.": "第一个工具链为默认工具链;CMake 配置可以选择其他工具链。", + "Toolchain settings": "工具链设置", + "Toolset": "工具集", + "Detect": "自动检测", + "Empty fields are detected: from the MinGW toolset, else from PATH. The compilers and the build tool are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "空字段会自动检测:先从 MinGW 工具集,再从 PATH。编译器和构建工具以 CMAKE_C_COMPILER、CMAKE_CXX_COMPILER 和 CMAKE_MAKE_PROGRAM 传给 CMake。", + "No answer to --version": "--version 无响应", + "Cache variables": "缓存变量", + "No CMakeCache.txt yet: the variables show once the profile is configured.": "尚无 CMakeCache.txt:配置该配置后会显示变量。", + "Show advanced": "显示高级", + "Detected: {name}": "已检测:{name}", + "Not saved yet: until a toolchain is edited or added, the tools found on PATH are used.": "尚未保存:在编辑或添加工具链之前,使用 PATH 中找到的工具。", "Compare Value with Clipboard": "将值与剪贴板比较", "Cannot compare the value": "无法比较该值", "The clipboard could not be read": "无法读取剪贴板",