The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
feat(run): Tomcat Server run configuration and application server dialogs (#1963)
RuyimgByCNe024c13db721
diff --git a/crates/ide-host/src/ops/run/commands.rs b/crates/ide-host/src/ops/run/commands.rsindex b1a6c867d..a0a553b4f 100644--- a/crates/ide-host/src/ops/run/commands.rs+++ b/crates/ide-host/src/ops/run/commands.rs@@ -181,6 +181,16 @@ pub async fn run_tomcat_home(host: &Host, window: &str, home: String) -> IdeResu.map_err(|e| IdeError::internal(e.to_string()))?}+pub async fn run_tomcat_installations(+ host: &Host,+ window: &str,+) -> IdeResult<Vec<ide_run::tomcat::TomcatInstallation>> {+ host.require_trust(window)?;+ tokio::task::spawn_blocking(ide_run::tomcat::detect_installations)+ .await+ .map_err(|e| IdeError::internal(e.to_string()))+}+pub async fn run_tomcat_artifacts(host: &Host, window: &str) -> IdeResult<Vec<ide_build::web::WebArtifact>> {host.require_trust(window)?;let project = host.project(window)?;@@ -212,7 +222,7 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I&project.root,&model,id,- &ide_run::tomcat::base_dir(&project.cache_dir, &config.id),+ &ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?,)?;plan.env.extend(config.env.clone());let mut build = RunConfig {@@ -278,7 +288,7 @@ pub async fn run_tomcat_sync(let module = dunce::canonicalize(project.root.join(module))?;let class_paths: Vec<_> =class_paths.iter().filter_map(|p| dunce::canonicalize(project.root.join(p)).ok()).collect();- let base = ide_run::tomcat::base_dir(&project.cache_dir, &config.id);+ let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;ide_run::tomcat::sync_outputs(&base, &module, &class_paths, resources_only)}).await@@ -297,6 +307,7 @@ pub(crate) fn register(d: &mut Dispatcher) {run_application_publish(&c.host, &c.window, c.arg("config")?, c.arg("classPaths")?, c.arg("mainClass")?).await});d.add("run_tomcat_home", |c| async move { run_tomcat_home(&c.host, &c.window, c.arg("home")?).await });+ d.add("run_tomcat_installations", |c| async move { run_tomcat_installations(&c.host, &c.window).await });d.add("run_tomcat_artifacts", |c| async move { run_tomcat_artifacts(&c.host, &c.window).await });d.add("run_tomcat_build", |c| async move { run_tomcat_build(&c.host, &c.window, c.arg("config")?).await });d.add("run_tomcat_sync", |c| async move {diff --git a/crates/ide-run/src/tomcat.rs b/crates/ide-run/src/tomcat.rsindex bcccc221b..1352976f6 100644--- a/crates/ide-run/src/tomcat.rs+++ b/crates/ide-run/src/tomcat.rs@@ -22,6 +22,232 @@ fn invalid(e: impl std::fmt::Display) -> IdeError {#[serde(rename_all = "camelCase")]pub struct TomcatHome {pub version: String,+ #[serde(default)]+ pub libraries: Vec<String>,+ #[serde(default)]+ pub tomee: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[specta(optional)]+ pub http_port: Option<u16>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[specta(optional)]+ pub https_port: Option<u16>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[specta(optional)]+ pub ajp_port: Option<u16>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[specta(optional)]+ pub shutdown_port: Option<u16>,+}++#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct TomcatInstallation {+ pub path: String,+ pub version: String,+ #[serde(default)]+ pub libraries: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[specta(optional)]+ pub name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[specta(optional)]+ pub base: Option<String>,+ #[serde(default)]+ pub tomee: bool,+}++pub fn is_tomee(home: &Path) -> bool {+ let Ok(entries) = fs::read_dir(home.join("lib")) else { return false };+ entries.flatten().any(|e| {+ e.path().file_name().and_then(|n| n.to_str()).is_some_and(|n| {+ let lower = n.to_ascii_lowercase();+ lower.ends_with(".jar") && (lower.starts_with("tomee-") || lower.starts_with("openejb-core-"))+ })+ })+}++pub fn read_server_xml_ports(xml: &str) -> (Option<u16>, Option<u16>, Option<u16>, Option<u16>) {+ let mut reader = Reader::from_str(xml);+ let mut http = None;+ let mut https = None;+ let mut ajp = None;+ let mut shutdown = None;+ while let Ok(event) = reader.read_event() {+ match event {+ Event::Eof => break,+ Event::Start(ref tag) | Event::Empty(ref tag) => {+ let name = tag.name().as_ref().to_owned();+ let attrs: Vec<(String, String)> = tag+ .attributes()+ .filter_map(|a| {+ let a = a.ok()?;+ let v = a.normalized_value(quick_xml::XmlVersion::Implicit1_0).ok()?.into_owned();+ Some((a.key.as_ref().to_owned(), v))+ })+ .collect();+ let attr_val =+ |k: &str| attrs.iter().find(|(key, _)| key.eq_ignore_ascii_case(k)).map(|(_, v)| v.as_str());+ let port = attr_val("port").and_then(|p| p.parse::<u16>().ok()).filter(|&p| p > 0);+ if name == "Server" && shutdown.is_none() {+ shutdown = port;+ } else if name == "Connector" {+ let protocol = attr_val("protocol").unwrap_or_default();+ let ssl = attr_val("SSLEnabled").is_some_and(|v| v.eq_ignore_ascii_case("true"))+ || attr_val("scheme").is_some_and(|v| v.eq_ignore_ascii_case("https"))+ || attr_val("secure").is_some_and(|v| v.eq_ignore_ascii_case("true"));+ let is_ajp = protocol.to_ascii_uppercase().contains("AJP");+ if ssl && https.is_none() {+ https = port;+ } else if is_ajp && ajp.is_none() {+ ajp = port;+ } else if !ssl+ && !is_ajp+ && http.is_none()+ && (protocol.is_empty() || protocol.contains("HTTP") || protocol.contains("Http"))+ {+ http = port;+ }+ }+ }+ _ => {}+ }+ }+ (http, https, ajp, shutdown)+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct IdeaTomcatServer {+ pub name: String,+ pub home: PathBuf,+ pub base: Option<PathBuf>,+ pub libraries: Vec<String>,+}++pub fn parse_idea_app_servers(xml: &str, user_home: &Path) -> Vec<IdeaTomcatServer> {+ let home_str = user_home.to_string_lossy();+ let expand = |raw: &str| -> String { raw.replace("$USER_HOME$", &home_str) };+ let mut reader = Reader::from_str(xml);+ let mut servers: Vec<IdeaTomcatServer> = Vec::new();+ let mut lib_map: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();+ let mut cur_server_name: Option<String> = None;+ let mut cur_integration: Option<String> = None;+ let mut cur_home: Option<String> = None;+ let mut cur_base: Option<String> = None;+ let mut cur_lib_name: Option<String> = None;+ let mut in_classes = false;++ while let Ok(event) = reader.read_event() {+ match event {+ Event::Eof => break,+ Event::Start(ref tag) | Event::Empty(ref tag) => {+ let tag_name = tag.name().as_ref().to_owned();+ let attr = |key: &str| -> Option<String> {+ tag.attributes().flatten().find(|a| a.key.as_ref().eq_ignore_ascii_case(key)).and_then(|a| {+ a.normalized_value(quick_xml::XmlVersion::Implicit1_0).ok().map(|v| v.into_owned())+ })+ };+ match tag_name.as_str() {+ "ServerDK" => {+ cur_server_name = attr("NAME");+ cur_integration = None;+ cur_home = None;+ cur_base = None;+ }+ "option" if cur_server_name.is_some() => {+ if let (Some(n), Some(v)) = (attr("name"), attr("value")) {+ match n.as_str() {+ "SOURCE_INTEGRATION_NAME" | "INTEGRATION_ID" => cur_integration = Some(v),+ "CATALINA_HOME" if !v.trim().is_empty() => cur_home = Some(expand(v.trim())),+ "CATALINA_BASE" if !v.trim().is_empty() => cur_base = Some(expand(v.trim())),+ _ => {}+ }+ }+ }+ "library" => {+ cur_lib_name = attr("name");+ }+ "CLASSES" if cur_lib_name.is_some() => {+ in_classes = true;+ }+ "root" if in_classes && cur_lib_name.is_some() => {+ if let Some(url) = attr("url") {+ let cleaned =+ url.strip_prefix("jar://").or_else(|| url.strip_prefix("file://")).unwrap_or(&url);+ let cleaned = cleaned.strip_suffix("!/").unwrap_or(cleaned);+ let expanded = expand(cleaned);+ if !expanded.is_empty()+ && let Some(ref lib_name) = cur_lib_name+ {+ lib_map.entry(lib_name.clone()).or_default().push(expanded);+ }+ }+ }+ _ => {}+ }+ }+ Event::End(ref tag) => match tag.name().as_ref() {+ "ServerDK" => {+ let is_tomcat =+ cur_integration.as_deref().is_none_or(|i| i.contains("Tomcat") || i.contains("TomEE"));+ if is_tomcat && let (Some(name), Some(home)) = (cur_server_name.take(), cur_home.take()) {+ servers.push(IdeaTomcatServer {+ name,+ home: PathBuf::from(home),+ base: cur_base.take().map(PathBuf::from),+ libraries: Vec::new(),+ });+ }+ cur_server_name = None;+ cur_integration = None;+ cur_home = None;+ cur_base = None;+ }+ "CLASSES" => {+ in_classes = false;+ }+ "library" => {+ cur_lib_name = None;+ in_classes = false;+ }+ _ => {}+ },+ _ => {}+ }+ }+ for srv in &mut servers {+ if let Some(libs) = lib_map.remove(&srv.name) {+ srv.libraries = libs;+ }+ }+ servers+}++pub fn discover_tomcat_libraries(home: &Path) -> Vec<String> {+ let lib_dir = home.join("lib");+ let mut out = Vec::new();+ for preferred in ["jsp-api.jar", "servlet-api.jar"] {+ let p = lib_dir.join(preferred);+ if p.is_file() {+ out.push(p.to_string_lossy().into_owned());+ }+ }+ if let Ok(entries) = fs::read_dir(&lib_dir) {+ let mut extras: Vec<String> = entries+ .flatten()+ .map(|e| e.path())+ .filter(|p| {+ p.is_file()+ && p.file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.ends_with("-api.jar") && !matches!(n, "jsp-api.jar" | "servlet-api.jar"))+ })+ .map(|p| p.to_string_lossy().into_owned())+ .collect();+ extras.sort();+ out.extend(extras);+ }+ out}pub fn validate_home(home: &Path) -> IdeResult<TomcatHome> {@@ -35,7 +261,127 @@ pub fn validate_home(home: &Path) -> IdeResult<TomcatHome> {jar.by_name("org/apache/catalina/util/ServerInfo.properties").map_err(invalid)?.read_to_string(&mut properties)?;let version =properties.lines().find_map(|l| l.strip_prefix("server.info=")).unwrap_or("Apache Tomcat").trim().to_owned();- Ok(TomcatHome { version })+ let libraries = discover_tomcat_libraries(home);+ let tomee = is_tomee(home);+ let (http_port, https_port, ajp_port, shutdown_port) = fs::read_to_string(home.join("conf/server.xml"))+ .ok()+ .map(|xml| read_server_xml_ports(&xml))+ .unwrap_or((None, None, None, None));+ Ok(TomcatHome { version, libraries, tomee, http_port, https_port, ajp_port, shutdown_port })+}++pub fn detect_installations() -> Vec<TomcatInstallation> {+ let mut seen = std::collections::HashSet::new();+ let mut found = Vec::new();+ let user_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);++ if let Some(ref home) = user_home {+ let mut jetbrains_roots =+ vec![home.join("Library/Application Support/JetBrains"), home.join(".config/JetBrains")];+ if let Some(appdata) = std::env::var_os("APPDATA") {+ jetbrains_roots.push(PathBuf::from(appdata).join("JetBrains"));+ }+ for jb_root in jetbrains_roots {+ let Ok(entries) = fs::read_dir(&jb_root) else { continue };+ let mut idea_dirs: Vec<PathBuf> = entries+ .flatten()+ .map(|e| e.path())+ .filter(|p| {+ p.file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.starts_with("IntelliJIdea") || n.starts_with("IdeaIC"))+ })+ .collect();+ idea_dirs.sort_by(|a, b| b.cmp(a));+ for dir in idea_dirs {+ let xml_path = dir.join("options/javaeeAppServers.xml");+ let Ok(xml) = fs::read_to_string(&xml_path) else { continue };+ for srv in parse_idea_app_servers(&xml, home) {+ let Ok(canon) = dunce::canonicalize(&srv.home) else { continue };+ if !seen.insert(canon.clone()) {+ continue;+ }+ if let Ok(info) = validate_home(&canon) {+ let base = srv+ .base+ .and_then(|b| dunce::canonicalize(b).ok())+ .filter(|b| b != &canon)+ .map(|b| b.to_string_lossy().into_owned());+ let libraries = if srv.libraries.is_empty() { info.libraries } else { srv.libraries };+ found.push(TomcatInstallation {+ path: canon.to_string_lossy().into_owned(),+ version: info.version,+ libraries,+ name: Some(srv.name).filter(|s| !s.trim().is_empty()),+ base,+ tomee: info.tomee,+ });+ }+ }+ }+ }+ }++ let mut candidates = Vec::new();+ for var in ["CATALINA_HOME", "TOMCAT_HOME"] {+ if let Some(val) = std::env::var_os(var).filter(|v| !v.is_empty()) {+ candidates.push(PathBuf::from(val));+ }+ }+ for brew_opt in ["/opt/homebrew/opt", "/usr/local/opt"] {+ let opt = Path::new(brew_opt);+ if let Ok(entries) = fs::read_dir(opt) {+ for entry in entries.flatten() {+ let name = entry.file_name();+ if name.to_string_lossy().starts_with("tomcat") {+ candidates.push(entry.path().join("libexec"));+ candidates.push(entry.path());+ }+ }+ }+ }+ let mut roots = vec![+ PathBuf::from("/Library"),+ PathBuf::from("/opt"),+ PathBuf::from("/usr/share"),+ PathBuf::from("/usr/local"),+ PathBuf::from("C:/Program Files/Apache Software Foundation"),+ PathBuf::from("C:/"),+ ];+ if let Some(ref home) = user_home {+ roots.push(home.join("Documents/tomcat"));+ roots.push(home.join("Documents"));+ roots.push(home.join("Downloads"));+ roots.push(home.join("Library"));+ roots.push(home.clone());+ }+ for root in roots {+ let Ok(entries) = fs::read_dir(&root) else { continue };+ for entry in entries.flatten() {+ let name = entry.file_name().to_string_lossy().to_ascii_lowercase();+ if name.starts_with("tomcat") || name.starts_with("apache-tomcat") || name.starts_with("apache-tomee") {+ candidates.push(entry.path());+ candidates.push(entry.path().join("libexec"));+ }+ }+ }+ for candidate in candidates {+ let Ok(canon) = dunce::canonicalize(&candidate) else { continue };+ if !seen.insert(canon.clone()) {+ continue;+ }+ if let Ok(info) = validate_home(&canon) {+ found.push(TomcatInstallation {+ path: canon.to_string_lossy().into_owned(),+ version: info.version,+ libraries: info.libraries,+ name: None,+ base: None,+ tomee: info.tomee,+ });+ }+ }+ found}pub fn base_dir(cache: &Path, id: &str) -> PathBuf {@@ -44,6 +390,50 @@ pub fn base_dir(cache: &Path, id: &str) -> PathBuf {cache.join("tomcat").join(key)}+/// Resolve existing ancestors before comparing paths, including aliases of a not-yet-created base.+fn canonical_path(path: &Path) -> IdeResult<PathBuf> {+ let mut resolved = PathBuf::new();+ for component in std::path::absolute(path)?.components() {+ match component {+ std::path::Component::ParentDir => {+ resolved.pop();+ }+ std::path::Component::CurDir => {}+ _ => resolved.push(component),+ }+ match dunce::canonicalize(&resolved) {+ Ok(path) => resolved = path,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound && fs::symlink_metadata(&resolved).is_err() => {}+ Err(e) => return Err(e.into()),+ }+ }+ Ok(resolved)+}++fn source_base_dir(root: &Path, config: &RunConfig) -> IdeResult<PathBuf> {+ let source = config+ .extras+ .params+ .get("tomcatBase")+ .filter(|s| !s.trim().is_empty())+ .or_else(|| config.extras.params.get("tomcatHome"))+ .ok_or_else(|| invalid("Choose a Tomcat installation directory"))?;+ canonical_path(&root.join(source.trim()))+}++/// All launch, build and update writes use this IDE-owned directory, never an installation source.+pub fn effective_base_dir(root: &Path, cache: &Path, config: &RunConfig) -> IdeResult<PathBuf> {+ let base = canonical_path(&base_dir(cache, &config.id))?;+ let home =+ config.extras.params.get("tomcatHome").ok_or_else(|| invalid("Choose a Tomcat installation directory"))?;+ for source in [canonical_path(&root.join(home.trim()))?, source_base_dir(root, config)?] {+ if base.starts_with(&source) || source.starts_with(&base) {+ return Err(invalid("IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory"));+ }+ }+ Ok(base)+}+pub fn free_port() -> IdeResult<u16> {Ok(TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port())}@@ -93,6 +483,20 @@ pub fn deployed_context_xml(doc_base: &Path, reload: bool) -> String {})}+pub fn deployed_context_xml_with_descriptor(+ doc_base: &Path,+ custom_descriptor: Option<&Path>,+ reload: bool,+) -> IdeResult<String> {+ let Some(custom) = custom_descriptor else {+ return Ok(deployed_context_xml(doc_base, reload));+ };+ let text = fs::read_to_string(custom)+ .map_err(|e| invalid(format!("Cannot read context descriptor {}: {e}", custom.display())))?;+ merge_context_xml(&text, doc_base, reload)+ .map_err(|e| invalid(format!("Invalid context descriptor {}: {e}", custom.display())))+}+fn merge_context_xml(app: &str, doc_base: &Path, reload: bool) -> IdeResult<String> {let mut reader = Reader::from_str(app);let mut writer = Writer::new(Vec::new());@@ -127,10 +531,24 @@ fn merge_context_xml(app: &str, doc_base: &Path, reload: bool) -> IdeResult<StriString::from_utf8(writer.into_inner()).map_err(invalid)}+#[derive(Clone, Copy, Debug, Default)]+pub struct TomcatPorts {+ pub http: u16,+ pub https: Option<u16>,+ pub ajp: Option<u16>,+ pub shutdown: u16,+}+pub fn patch_server_xml(xml: &str, http: u16, shutdown: u16, secret: &str) -> IdeResult<String> {+ patch_server_xml_with_ports(xml, TomcatPorts { http, https: None, ajp: None, shutdown }, secret)+}++pub fn patch_server_xml_with_ports(xml: &str, ports: TomcatPorts, secret: &str) -> IdeResult<String> {let mut reader = Reader::from_str(xml);let mut writer = Writer::new(Vec::new());let mut http_found = false;+ let mut https_found = false;+ let mut ajp_found = false;loop {let event = reader.read_event().map_err(invalid)?;if matches!(event, Event::Eof) {@@ -149,27 +567,47 @@ pub fn patch_server_xml(xml: &str, http: u16, shutdown: u16, secret: &str) -> Id))}).collect::<IdeResult<_>>()?;+ let (protocol, ssl, ajp) = {+ let attr_val =+ |k: &str| attrs.iter().find(|(key, _)| key.eq_ignore_ascii_case(k)).map(|(_, v)| v.as_str());+ let protocol = attr_val("protocol").unwrap_or_default().to_owned();+ let ssl = attr_val("SSLEnabled").is_some_and(|v| v.eq_ignore_ascii_case("true"))+ || attr_val("scheme").is_some_and(|v| v.eq_ignore_ascii_case("https"))+ || attr_val("secure").is_some_and(|v| v.eq_ignore_ascii_case("true"));+ let ajp = protocol.to_ascii_uppercase().contains("AJP");+ (protocol, ssl, ajp)+ };let mut set = |key: &str, value: String| {attrs.retain(|(k, _)| k != key);attrs.push((key.into(), value));};match name.as_str() {"Server" => {- set("port", shutdown.to_string());+ set("port", ports.shutdown.to_string());set("address", "127.0.0.1".into());set("shutdown", secret.into());}"Connector" => {- let protocol = tag- .try_get_attribute("protocol")- .map_err(invalid)?- .map(|a| a.value.into_owned())- .unwrap_or_default();- let is_http = !http_found- && (protocol.is_empty() || protocol.contains("HTTP") || protocol.contains("Http"));- set("port", if is_http { http } else { free_port()? }.to_string());- if is_http {+ if ssl && !https_found {+ let p = ports.https.map_or_else(free_port, Ok)?;+ set("port", p.to_string());+ https_found = true;+ } else if ajp && !ajp_found {+ let p = ports.ajp.map_or_else(free_port, Ok)?;+ set("port", p.to_string());+ ajp_found = true;+ } else if !ssl+ && !ajp+ && !http_found+ && (protocol.is_empty() || protocol.contains("HTTP") || protocol.contains("Http"))+ {+ set("port", ports.http.to_string());http_found = true;+ if let Some(https_port) = ports.https {+ set("redirectPort", https_port.to_string());+ }+ } else {+ set("port", free_port()?.to_string());}}"Engine" => set("name", "Catalina".into()),@@ -194,6 +632,12 @@ pub fn patch_server_xml(xml: &str, http: u16, shutdown: u16, secret: &str) -> Idif !http_found {return Err(invalid("Tomcat server.xml has no HTTP connector"));}+ if ports.https.is_some() && !https_found {+ return Err(invalid("Tomcat server.xml has no HTTPS connector"));+ }+ if ports.ajp.is_some() && !ajp_found {+ return Err(invalid("Tomcat server.xml has no AJP connector"));+ }String::from_utf8(writer.into_inner()).map_err(invalid)}@@ -460,47 +904,117 @@ pub fn script_command(home: &Path, windows: bool, verb: &str) -> (String, Vec<St}}+fn parse_optional_port(+ params: &std::collections::BTreeMap<String, String>,+ key: &str,+ label: &str,+) -> IdeResult<Option<u16>> {+ let Some(raw) = params.get(key).map(|s| s.trim()).filter(|s| !s.is_empty()) else {+ return Ok(None);+ };+ let port: u16 = raw.parse().map_err(|_| invalid(format!("{label} must be between 1 and 65535")))?;+ if port == 0 {+ return Err(invalid(format!("{label} must be between 1 and 65535")));+ }+ Ok(Some(port))+}++pub fn patch_catalina_properties(props: &str, extra_jars: &[String]) -> String {+ if extra_jars.is_empty() {+ return props.to_owned();+ }+ let suffix: String = extra_jars.iter().map(|j| format!(",\"{}\"", j.replace('\\', "/"))).collect();+ let mut patched = false;+ let mut lines: Vec<String> = props+ .lines()+ .map(|l| {+ if l.trim_start().starts_with("common.loader=") && !l.ends_with('\\') {+ patched = true;+ format!("{l}{suffix}")+ } else {+ l.to_owned()+ }+ })+ .collect();+ if !patched {+ lines.push(format!("common.loader=\"${{catalina.base}}/lib\",\"${{catalina.base}}/lib/*.jar\",\"${{catalina.home}}/lib\",\"${{catalina.home}}/lib/*.jar\"{suffix}"));+ }+ let mut out = lines.join("\n");+ out.push('\n');+ out+}+pub fn prepare(root: &Path, cache: &Path, config: &mut RunConfig) -> IdeResult<()> {// Batch scripts and their environment variables require ordinary Windows paths.let home = dunce::canonicalize(root.join(config.extras.params.get("tomcatHome").ok_or_else(|| invalid("Choose a Tomcat installation directory"))?,))?;validate_home(&home)?;- let base = base_dir(cache, &config.id);- fs::create_dir_all(&base)?;- let base = dunce::canonicalize(&base)?;- let doc = deployment(root, &base, config, false)?;- let context = effective_context(config, &doc);- let context = context_name(&context)?;+ let base = effective_base_dir(root, cache, config)?;+ let source = source_base_dir(root, config)?;let port: u16 =config.extras.params.get("httpPort").map(String::as_str).unwrap_or("8080").parse().map_err(invalid)?;if port == 0 {return Err(invalid("HTTP port must be between 1 and 65535"));}- let shutdown = free_port()?;+ let https = parse_optional_port(&config.extras.params, "httpsPort", "HTTPS port")?;+ let ajp = parse_optional_port(&config.extras.params, "ajpPort", "AJP port")?;+ let shutdown =+ parse_optional_port(&config.extras.params, "shutdownPort", "Shutdown port")?.map_or_else(free_port, Ok)?;+ let jmx = parse_optional_port(&config.extras.params, "jmxPort", "JMX port")?.map_or_else(free_port, Ok)?;let secret = format!("OPENIDEA_{}_{}",std::process::id(),std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(invalid)?.as_nanos());- // Refresh only the IDE-owned configuration, leaving logs and deployed artifacts available.- if base.join("conf").exists() {- fs::remove_dir_all(base.join("conf"))?;+ let server = patch_server_xml_with_ports(+ &fs::read_to_string(source.join("conf/server.xml"))?,+ TomcatPorts { http: port, https, ajp, shutdown },+ &secret,+ )?;+ // Build runs before prepare; retain its archive identity while recreating the runtime.+ let metadata: Vec<_> = ["artifact-path.txt", "artifact-id.txt", "artifact-project.txt"]+ .into_iter()+ .filter_map(|name| fs::read(base.join(name)).ok().map(|bytes| (name, bytes)))+ .collect();+ if base.exists() {+ fs::remove_dir_all(&base)?;}- copy_tree(&home.join("conf"), &base.join("conf"))?;- let contexts = base.join("conf/Catalina/localhost");- if contexts.exists() {- fs::remove_dir_all(&contexts)?;+ fs::create_dir_all(&base)?;+ for (name, bytes) in metadata {+ fs::write(base.join(name), bytes)?;+ }+ copy_tree(&source.join("conf"), &base.join("conf"))?;+ let deploy_apps = config.extras.params.get("deployTomcatApps").is_some_and(|v| v == "true");+ let hosts = base.join("conf/Catalina");+ if !deploy_apps && hosts.is_dir() {+ for host in fs::read_dir(hosts)? {+ let host = host?;+ if host.file_type()?.is_dir() {+ for descriptor in fs::read_dir(host.path())? {+ let path = descriptor?.path();+ if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("xml")) {+ fs::remove_file(path)?;+ }+ }+ }+ }}for dir in ["logs", "temp", "work", "webapps", "conf/Catalina/localhost"] {fs::create_dir_all(base.join(dir))?;}- let server = patch_server_xml(&fs::read_to_string(home.join("conf/server.xml"))?, port, shutdown, &secret)?;+ if deploy_apps && source.join("webapps").is_dir() {+ copy_tree(&source.join("webapps"), &base.join("webapps"))?;+ }+ let doc = deployment(root, &base, config, false)?;+ let context = context_name(&effective_context(config, &doc))?;+ let contexts = base.join("conf/Catalina/localhost");fs::write(base.join("conf/server.xml"), server)?;let debug = config.extras.params.get("tomcatDebug").is_some_and(|v| v == "true");- fs::write(contexts.join(format!("{context}.xml")), deployed_context_xml(&doc, !debug))?;- config.env.insert("CATALINA_HOME".into(), home.to_string_lossy().into_owned());- config.env.insert("CATALINA_BASE".into(), base.to_string_lossy().into_owned());+ let custom_descriptor =+ config.extras.params.get("contextDescriptor").map(|s| s.trim()).filter(|s| !s.is_empty()).map(|s| root.join(s));+ let context_xml_content = deployed_context_xml_with_descriptor(&doc, custom_descriptor.as_deref(), !debug)?;+ fs::write(contexts.join(format!("{context}.xml")), context_xml_content)?;if let Some(jre) = config.extras.params.get("jre").filter(|s| !s.trim().is_empty()) {let jre = dunce::canonicalize(root.join(jre))?;config.env.insert("JAVA_HOME".into(), jre.to_string_lossy().into_owned());@@ -509,19 +1023,78 @@ pub fn prepare(root: &Path, cache: &Path, config: &mut RunConfig) -> IdeResult<(config.env.insert("JRE_HOME".into(), java);}let vm = config.extras.params.get("vmOptions").cloned().unwrap_or_default();- let jmx = free_port()?;let mut opts = config.env.get("CATALINA_OPTS").cloned().unwrap_or_default();opts.push_str(&format!(" {vm} -Dcom.sun.management.jmxremote.port={jmx} -Dcom.sun.management.jmxremote.rmi.port={jmx} -Dcom.sun.management.jmxremote.host=127.0.0.1 -Djava.rmi.server.hostname=127.0.0.1 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"));if debug {- opts.push_str(" -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:0");+ let jdwp_port = parse_optional_port(&config.extras.params, "debugPort", "Debug port")?.unwrap_or(0);+ opts.push_str(&format!(" -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:{jdwp_port}"));}config.env.insert("CATALINA_OPTS".into(), opts);- (config.command, config.args) = script_command(&home, cfg!(windows), "run");- config.extras.stop_command = Some(if cfg!(windows) {- script_command(&home, true, "stop").0+ if let Some(libs) = config.extras.params.get("tomcatLibraries").map(|s| s.trim()).filter(|s| !s.is_empty()) {+ let sep = if cfg!(windows) { ";" } else { ":" };+ let lib_items: Vec<String> = libs.split(';').map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect();+ let joined = lib_items.join(sep);+ if !joined.is_empty() {+ config.env.insert("CLASSPATH".into(), joined);+ }+ let home_lib = home.join("lib");+ let extra_jars: Vec<String> = lib_items.into_iter().filter(|j| !Path::new(j).starts_with(&home_lib)).collect();+ let cat_props_path = base.join("conf/catalina.properties");+ if !extra_jars.is_empty()+ && let Ok(props) = fs::read_to_string(&cat_props_path)+ {+ fs::write(&cat_props_path, patch_catalina_properties(&props, &extra_jars))?;+ }+ }+ if config.extras.params.get("passEnvVars").map(String::as_str) != Some("false") {+ let env_key = if debug { "startupEnvDebug" } else { "startupEnvRun" };+ if let Some(raw_env) = config.extras.params.get(env_key).or_else(|| config.extras.params.get("startupEnv")) {+ for pair in raw_env.split('\n').map(str::trim).filter(|s| !s.is_empty()) {+ if let Some((k, v)) = pair.split_once('=') {+ let k = k.trim();+ if !k.is_empty() {+ config.env.insert(k.to_owned(), v.to_owned());+ }+ }+ }+ }+ }+ config.env.insert("CATALINA_HOME".into(), home.to_string_lossy().into_owned());+ config.env.insert("CATALINA_BASE".into(), base.to_string_lossy().into_owned());+ let use_custom_start = config.extras.params.get("useDefaultStartup").map(String::as_str) == Some("false");+ if use_custom_start+ && let Some(custom_start) =+ config.extras.params.get("startupScript").map(|s| s.trim()).filter(|s| !s.is_empty())+ {+ let script = root.join(custom_start);+ if cfg!(windows) {+ config.command = format!("\"{}\"", script.display());+ config.args = vec![];+ } else {+ config.command = "sh".into();+ config.args = vec![script.to_string_lossy().into_owned()];+ }} else {- format!("sh '{}' stop", home.join("bin/catalina.sh").to_string_lossy().replace('\'', "'\\''"))- });+ (config.command, config.args) = script_command(&home, cfg!(windows), "run");+ }+ let use_custom_stop = config.extras.params.get("useDefaultShutdown").map(String::as_str) == Some("false");+ config.extras.stop_command = Some(+ if use_custom_stop+ && let Some(custom_stop) =+ config.extras.params.get("shutdownScript").map(|s| s.trim()).filter(|s| !s.is_empty())+ {+ let script = root.join(custom_stop);+ if cfg!(windows) {+ format!("\"{}\"", script.display())+ } else {+ format!("sh '{}'", script.to_string_lossy().replace('\'', "'\\''"))+ }+ } else if cfg!(windows) {+ script_command(&home, true, "stop").0+ } else {+ format!("sh '{}' stop", home.join("bin/catalina.sh").to_string_lossy().replace('\'', "'\\''"))+ },+ );config.extras.emulate_terminal = false;Ok(())}@@ -530,7 +1103,7 @@ pub fn update(root: &Path, cache: &Path, config: &RunConfig, mode: &str) -> IdeRif !matches!(mode, "resources" | "classes" | "redeploy") {return Err(invalid("Unknown Tomcat update operation"));}- let base = base_dir(cache, &config.id);+ let base = effective_base_dir(root, cache, config)?;let doc = deployment(root, &base, config, mode == "resources")?;let context = context_name(&effective_context(config, &doc))?;let file = base.join("conf/Catalina/localhost").join(format!("{context}.xml"));@@ -837,6 +1410,27 @@ mod tests {let root = PathBuf::from(format!(r"\\?\{}", dunce::canonicalize(tmp.path()).unwrap().display()));check_prepared_paths(&root);}+ #[test]+ fn requires_existing_optional_connectors_and_keeps_http_separate_from_tls() {+ let xml = "<Server><Connector port='8443' SSLEnabled='true'/><Connector port='9443' SSLEnabled='true'/><Connector port='8080'/></Server>";+ assert_eq!(read_server_xml_ports(xml), (Some(8080), Some(8443), None, None));+ let patched = patch_server_xml_with_ports(+ xml,+ TomcatPorts { http: 18080, https: Some(18443), shutdown: 18005, ajp: None },+ "secret",+ )+ .unwrap();+ assert!(patched.contains("port=\"18080\""));+ assert!(patched.contains("port=\"18443\""));+ let plain = "<Server><Connector port='8080'/></Server>";+ for (https, ajp, label) in [(Some(8443), None, "HTTPS"), (None, Some(8009), "AJP")] {+ let error =+ patch_server_xml_with_ports(plain, TomcatPorts { http: 8080, https, ajp, shutdown: 8005 }, "secret")+ .unwrap_err();+ assert!(error.to_string().contains(label));+ }+ }+fn check_prepared_paths(root: &Path) {let home = root.join("Tomcat Home");fs::create_dir_all(home.join("bin")).unwrap();@@ -892,5 +1486,320 @@ mod tests {assert!(!c.extras.stop_command.as_ref().unwrap().contains(r"\\?\"));assert!(c.env.values().all(|value| !value.contains(r"\\?\")));assert!(!fs::read_to_string(context).unwrap().contains(r"\\?\"));+ // Serialized library lists use semicolons, including Windows drive letters.+ c.env.remove("CATALINA_OPTS");+ c.extras+ .params+ .insert("tomcatLibraries".into(), r"C:\Tomcat\lib\servlet-api.jar;D:\extra lib\extra.jar".into());+ c.extras.params.insert("startupEnvDebug".into(), "EMPTY=\nJAVA_OPTS=-Dmode=debug".into());+ prepare(root, &cache, &mut c).unwrap();+ let separator = if cfg!(windows) { ";" } else { ":" };+ assert_eq!(c.env["CLASSPATH"], [r"C:\Tomcat\lib\servlet-api.jar", r"D:\extra lib\extra.jar"].join(separator));+ assert_eq!(c.env["EMPTY"], "");+ assert_eq!(c.env["JAVA_OPTS"], "-Dmode=debug");+ assert_eq!(c.env["CATALINA_OPTS"].matches("-agentlib:jdwp").count(), 1);+ }++ #[test]+ fn supports_idea_custom_base_ports_context_descriptor_and_instance_webapps() {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ let home = root.join("Tomcat Home");+ fs::create_dir_all(home.join("bin")).unwrap();+ fs::create_dir_all(home.join("conf")).unwrap();+ fs::create_dir_all(home.join("webapps/manager")).unwrap();+ fs::write(home.join("webapps/manager/index.html"), "manager").unwrap();+ fs::create_dir_all(root.join("WebRoot")).unwrap();+ fs::write(home.join("bin/catalina.sh"), "").unwrap();+ fs::write(home.join("bin/catalina.bat"), "").unwrap();+ archive(+ &home.join("lib/catalina.jar"),+ &[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat/10.1")],+ );+ fs::write(home.join("lib/jsp-api.jar"), "").unwrap();+ fs::write(home.join("lib/servlet-api.jar"), "").unwrap();+ let validated = validate_home(&home).unwrap();+ assert_eq!(validated.libraries.len(), 2);+ assert!(validated.libraries[0].ends_with("jsp-api.jar"));+ assert!(validated.libraries[1].ends_with("servlet-api.jar"));+ let server = "<Server port='8005'><Service><Connector port='8080' protocol='HTTP/1.1'/><Connector port='8443' protocol='HTTP/1.1' SSLEnabled='true'/><Connector port='8009' protocol='AJP/1.3'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";+ fs::write(home.join("conf/server.xml"), server).unwrap();+ fs::write(+ root.join("custom-context.xml"),+ "<Context privileged=\"true\"><Parameter name=\"env\" value=\"dev\"/></Context>",+ )+ .unwrap();++ let mut c = config();+ for (k, v) in [+ ("tomcatHome", "Tomcat Home"),+ ("tomcatBase", "custom-base"),+ ("deployment", "directory"),+ ("deploymentPath", "WebRoot"),+ ("contextPath", "/app"),+ ("contextDescriptor", "custom-context.xml"),+ ("httpPort", "18080"),+ ("httpsPort", "18443"),+ ("ajpPort", "18009"),+ ("shutdownPort", "18005"),+ ("jmxPort", "11099"),+ ("deployTomcatApps", "true"),+ ("preserveSessions", "false"),+ ] {+ c.extras.params.insert(k.into(), v.into());+ }+ let source = root.join("custom-base");+ copy_tree(&home.join("conf"), &source.join("conf")).unwrap();+ copy_tree(&home.join("webapps"), &source.join("webapps")).unwrap();+ let cache = root.join("cache");+ prepare(root, &cache, &mut c).unwrap();++ let base = PathBuf::from(&c.env["CATALINA_BASE"]);+ assert_eq!(base, dunce::canonicalize(base_dir(&cache, &c.id)).unwrap());+ let patched_server = fs::read_to_string(base.join("conf/server.xml")).unwrap();+ assert!(patched_server.contains("port=\"18005\""));+ assert!(patched_server.contains("port=\"18080\""));+ assert!(patched_server.contains("redirectPort=\"18443\""));+ assert!(patched_server.contains("port=\"18443\""));+ assert!(patched_server.contains("port=\"18009\""));+ assert!(base.join("webapps/manager/index.html").is_file());+ let ctx_xml = fs::read_to_string(base.join("conf/Catalina/localhost/app.xml")).unwrap();+ assert!(ctx_xml.contains("privileged=\"true\""));+ assert!(ctx_xml.contains("<Parameter name=\"env\" value=\"dev\"/>"));+ assert!(c.env["CATALINA_OPTS"].contains("-Dcom.sun.management.jmxremote.port=11099"));+ }++ fn tree_hash(root: &Path) -> u64 {+ use std::hash::{Hash, Hasher};+ fn hash(dir: &Path, state: &mut std::hash::DefaultHasher) {+ let mut entries: Vec<_> = fs::read_dir(dir).unwrap().map(Result::unwrap).collect();+ entries.sort_by_key(|entry| entry.file_name());+ for entry in entries {+ entry.file_name().hash(state);+ let directory = entry.file_type().unwrap().is_dir();+ directory.hash(state);+ if directory {+ hash(&entry.path(), state);+ } else {+ fs::read(entry.path()).unwrap().hash(state);+ }+ }+ }+ let mut state = std::hash::DefaultHasher::new();+ hash(root, &mut state);+ state.finish()+ }++ #[test]+ fn recreates_owned_runtime_from_read_only_sources_with_optional_instance_apps() {+ for custom in [false, true] {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ check_prepared_paths(root);+ let home = root.join("Tomcat Home");+ let source = if custom { root.join("custom-base") } else { home.clone() };+ if custom {+ copy_tree(&home.join("conf"), &source.join("conf")).unwrap();+ }+ for host in ["localhost", "other-host"] {+ let descriptors = source.join("conf/Catalina").join(host);+ fs::create_dir_all(&descriptors).unwrap();+ fs::write(descriptors.join("existing.xml"), "<Context reloadable='false'/>").unwrap();+ }+ fs::create_dir_all(source.join("webapps/instance-app")).unwrap();+ fs::write(source.join("webapps/instance-app/index.html"), "instance").unwrap();+ fs::write(source.join("conf/source.properties"), "from=source").unwrap();+ // The configured base, rather than HOME, supplies configuration and applications.+ if custom {+ fs::create_dir_all(home.join("webapps/home-only")).unwrap();+ fs::write(home.join("webapps/home-only/index.html"), "home").unwrap();+ fs::write(+ source.join("conf/server.xml"),+ fs::read_to_string(home.join("conf/server.xml"))+ .unwrap()+ .replace("<Server ", "<Server source='custom' "),+ )+ .unwrap();+ }+ let before_home = tree_hash(&home);+ let before_source = tree_hash(&source);+ let cache = root.join("cache");+ let mut c = config();+ c.extras.params.insert("tomcatHome".into(), "Tomcat Home".into());+ if custom {+ c.extras.params.insert("tomcatBase".into(), "custom-base".into());+ }+ c.extras.params.insert("artifact".into(), "maven:pom.xml".into());+ let base = effective_base_dir(root, &cache, &c).unwrap();+ fs::create_dir_all(&base).unwrap();+ let war = root.join("app.war");+ archive(&war, &[("WEB-INF/web.xml", "<web-app/>"), ("index.html", "app")]);+ fs::write(base.join("artifact-path.txt"), war.to_string_lossy().as_bytes()).unwrap();+ fs::write(base.join("artifact-id.txt"), "maven:pom.xml").unwrap();+ c.extras.params.insert("contextPath".into(), "/app".into());+ c.extras.params.insert("httpPort".into(), "18080".into());+ c.extras+ .params+ .insert("startupEnvRun".into(), format!("CATALINA_BASE={}\nCATALINA_HOME=wrong", source.display()));+ for deploy in [true, false, true] {+ fs::create_dir_all(base.join("work")).unwrap();+ fs::write(base.join("work/stale"), "old runtime").unwrap();+ c.extras.params.insert("deployTomcatApps".into(), deploy.to_string());+ prepare(root, &cache, &mut c).unwrap();+ assert_eq!(PathBuf::from(&c.env["CATALINA_BASE"]), base);+ assert_eq!(PathBuf::from(&c.env["CATALINA_HOME"]), dunce::canonicalize(&home).unwrap());+ assert!(!base.join("work/stale").exists());+ for dir in ["logs", "temp", "work"] {+ assert!(base.join(dir).is_dir());+ }+ assert_eq!(fs::read_to_string(base.join("conf/source.properties")).unwrap(), "from=source");+ let server = fs::read_to_string(base.join("conf/server.xml")).unwrap();+ assert!(server.contains("port=\"18080\""));+ assert_eq!(server.contains("source=\"custom\""), custom);+ assert_eq!(base.join("webapps/instance-app/index.html").exists(), deploy);+ assert!(!base.join("webapps/home-only").exists());+ for host in ["localhost", "other-host"] {+ let descriptor = base.join("conf/Catalina").join(host).join("existing.xml");+ assert_eq!(descriptor.exists(), deploy);+ if deploy {+ assert_eq!(+ fs::read(descriptor).unwrap(),+ fs::read(source.join("conf/Catalina").join(host).join("existing.xml")).unwrap()+ );+ }+ }+ assert!(base.join("conf/Catalina/localhost/app.xml").is_file());+ assert!(base.join("deployment/WEB-INF/web.xml").is_file());+ update(root, &cache, &c, "redeploy").unwrap();+ assert_eq!(tree_hash(&home), before_home);+ assert_eq!(tree_hash(&source), before_source);+ }+ }+ }++ #[test]+ fn rejects_runtime_overlapping_either_source_before_any_write() {+ let tmp = tempfile::tempdir().unwrap();+ check_prepared_paths(tmp.path());+ let root = dunce::canonicalize(tmp.path()).unwrap();+ let cache = root.join("cache");+ let mut c = config();+ c.extras.params.insert("tomcatHome".into(), "Tomcat Home".into());+ let base = base_dir(&cache, &c.id);+ for source in [base.clone(), base.join("nested"), cache.clone()] {+ for key in ["tomcatHome", "tomcatBase"] {+ let mut c = c.clone();+ c.extras.params.insert(key.into(), source.to_string_lossy().into_owned());+ let before = tree_hash(&root);+ assert!(effective_base_dir(&root, &cache, &c).unwrap_err().to_string().contains("must not overlap"));+ assert!(prepare(&root, &cache, &mut c).is_err());+ assert!(update(&root, &cache, &c, "redeploy").is_err());+ assert_eq!(tree_hash(&root), before);+ }+ }+ }++ #[cfg(unix)]+ #[test]+ fn rejects_runtime_overlaps_through_symlink_aliases() {+ let tmp = tempfile::tempdir().unwrap();+ check_prepared_paths(tmp.path());+ let root = tmp.path();+ let home = root.join("Tomcat Home");+ let alias = root.join("alias");+ std::os::unix::fs::symlink(&home, &alias).unwrap();+ let mut c = config();+ c.extras.params.insert("tomcatHome".into(), "Tomcat Home".into());+ let before = tree_hash(&home);+ assert!(effective_base_dir(root, &alias.join("missing-cache"), &c).is_err());+ assert!(prepare(root, &alias.join("missing-cache"), &mut c).is_err());+ let cache = root.join("cache");+ let base = base_dir(&cache, &c.id);+ fs::remove_dir_all(&base).unwrap();+ std::os::unix::fs::symlink(&home, &base).unwrap();+ assert!(effective_base_dir(root, &cache, &c).is_err());+ assert!(prepare(root, &cache, &mut c).is_err());+ assert!(update(root, &cache, &c, "resources").is_err());+ assert_eq!(tree_hash(&home), before);+ fs::remove_file(&base).unwrap();+ fs::create_dir_all(&base).unwrap();+ let source_alias = root.join("base-alias");+ std::os::unix::fs::symlink(&base, &source_alias).unwrap();+ c.extras.params.insert("tomcatBase".into(), source_alias.to_string_lossy().into_owned());+ assert!(effective_base_dir(root, &cache, &c).is_err());+ }++ #[test]+ fn imports_idea_app_servers_detects_tomee_reads_server_xml_ports_and_patches_catalina_properties() {+ let idea_xml = r#"<application>+ <component name="AppserversManager">+ <ServerDK NAME="Tomcat 9.0.78">+ <option name="SOURCE_INTEGRATION_NAME" value="Tomcat Server" />+ <DATA>+ <option name="CATALINA_HOME" value="$USER_HOME$/Documents/tomcat/apache-tomcat-9.0.82" />+ <option name="CATALINA_BASE" value="" />+ </DATA>+ </ServerDK>+ <ServerDK NAME="Tomcat10">+ <option name="SOURCE_INTEGRATION_NAME" value="Tomcat Server" />+ <DATA>+ <option name="CATALINA_HOME" value="$USER_HOME$/Documents/tomcat/apache-tomcat-10.1.57" />+ <option name="CATALINA_BASE" value="$USER_HOME$/Documents/tomcat/base-10" />+ </DATA>+ </ServerDK>+ <LibraryTable>+ <library name="Tomcat10">+ <CLASSES>+ <root url="jar://$USER_HOME$/Documents/tomcat/apache-tomcat-10.1.57/lib/jsp-api.jar!/" />+ <root url="jar://$USER_HOME$/Documents/tomcat/apache-tomcat-10.1.57/lib/servlet-api.jar!/" />+ </CLASSES>+ </library>+ </LibraryTable>+ </component>+</application>"#;+ let parsed = parse_idea_app_servers(idea_xml, Path::new("/Users/demo"));+ assert_eq!(parsed.len(), 2);+ assert_eq!(parsed[0].name, "Tomcat 9.0.78");+ assert_eq!(parsed[0].home, PathBuf::from("/Users/demo/Documents/tomcat/apache-tomcat-9.0.82"));+ assert_eq!(parsed[0].base, None);+ assert_eq!(parsed[1].name, "Tomcat10");+ assert_eq!(parsed[1].home, PathBuf::from("/Users/demo/Documents/tomcat/apache-tomcat-10.1.57"));+ assert_eq!(parsed[1].base, Some(PathBuf::from("/Users/demo/Documents/tomcat/base-10")));+ assert_eq!(+ parsed[1].libraries,+ vec![+ "/Users/demo/Documents/tomcat/apache-tomcat-10.1.57/lib/jsp-api.jar",+ "/Users/demo/Documents/tomcat/apache-tomcat-10.1.57/lib/servlet-api.jar",+ ]+ );++ let server_xml = "<Server port='8005'><Service><Connector port='8080' protocol='HTTP/1.1'/><Connector port='8443' SSLEnabled='true'/><Connector port='8009' protocol='AJP/1.3'/></Service></Server>";+ assert_eq!(read_server_xml_ports(server_xml), (Some(8080), Some(8443), Some(8009), Some(8005)));++ let patched_props = patch_catalina_properties(+ "package.access=sun.\ncommon.loader=\"${catalina.base}/lib\",\"${catalina.home}/lib/*.jar\"\n",+ &["/opt/extra/driver.jar".into()],+ );+ assert!(patched_props.contains(+ "common.loader=\"${catalina.base}/lib\",\"${catalina.home}/lib/*.jar\",\"/opt/extra/driver.jar\""+ ));++ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("tomee");+ fs::create_dir_all(home.join("bin")).unwrap();+ fs::create_dir_all(home.join("conf")).unwrap();+ fs::write(home.join("bin/catalina.sh"), "").unwrap();+ archive(+ &home.join("lib/catalina.jar"),+ &[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat (TomEE)/9.0.82\n")],+ );+ fs::write(home.join("lib/tomee-catalina-9.1.2.jar"), "").unwrap();+ fs::write(home.join("conf/server.xml"), server_xml).unwrap();+ let info = validate_home(&home).unwrap();+ assert!(info.tomee);+ assert_eq!(info.http_port, Some(8080));+ assert_eq!(info.https_port, Some(8443));+ assert_eq!(info.ajp_port, Some(8009));+ assert_eq!(info.shutdown_port, Some(8005));}}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 335e9f52d..454c924b1 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -362,6 +362,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {run::run_gradle_jvm_args_script,run::run_gradle_init_script,run::run_tomcat_home,+ run::run_tomcat_installations,run::run_tomcat_artifacts,run::run_tomcat_build,run::run_application_build,diff --git a/src-tauri/src/commands/run.rs b/src-tauri/src/commands/run.rsindex d53b89a14..0be1dd525 100644--- a/src-tauri/src/commands/run.rs+++ b/src-tauri/src/commands/run.rs@@ -225,6 +225,14 @@ pub async fn run_tomcat_home(}#[tauri::command]#[specta::specta]+pub async fn run_tomcat_installations(+ window: Window,+ state: State<'_, AppState>,+) -> IdeResult<Vec<ide_run::tomcat::TomcatInstallation>> {+ ide_host::ops::run::run_tomcat_installations(&state.host, window.label()).await+}+#[tauri::command]+#[specta::specta]pub async fn run_tomcat_artifacts(window: Window,state: State<'_, AppState>,diff --git a/src/bindings.ts b/src/bindings.tsindex 947abd83d..6e6bdbc58 100644--- a/src/bindings.ts+++ b/src/bindings.ts@@ -682,7 +682,8 @@ export const commands = {runGradleJvmArgsScript: (jvmArgs: string[]) => typedError<string, IdeError>(__TAURI_INVOKE("run_gradle_jvm_args_script", { jvmArgs })),/** Writes one of the IDE's Gradle init scripts where the build runs; returns its path. */runGradleInitScript: (name: string, text: string) => typedError<string, IdeError>(__TAURI_INVOKE("run_gradle_init_script", { name, text })),- runTomcatHome: (home: string) => typedError<TomcatHome, IdeError>(__TAURI_INVOKE("run_tomcat_home", { home })),+ runTomcatHome: (home: string) => typedError<TomcatHome_Serialize, IdeError>(__TAURI_INVOKE("run_tomcat_home", { home })),+ runTomcatInstallations: () => typedError<TomcatInstallation_Serialize[], IdeError>(__TAURI_INVOKE("run_tomcat_installations")),runTomcatArtifacts: () => typedError<WebArtifact[], IdeError>(__TAURI_INVOKE("run_tomcat_artifacts")),runTomcatBuild: (config: RunConfig_Deserialize) => typedError<({/** Stable id, e.g. `npm:dev`, `cargo:run:app`, or a uuid for user-defined. */@@ -7914,8 +7915,46 @@ export type ThreadInfo = {name: string,};-export type TomcatHome = {+export type TomcatHome = TomcatHome_Serialize | TomcatHome_Deserialize;++export type TomcatHome_Deserialize = {+ version: string,+ libraries?: string[],+ tomee?: boolean,+ httpPort?: number | null,+ httpsPort?: number | null,+ ajpPort?: number | null,+ shutdownPort?: number | null,+};++export type TomcatHome_Serialize = {+ version: string,+ libraries: string[],+ tomee: boolean,+ httpPort?: number | null,+ httpsPort?: number | null,+ ajpPort?: number | null,+ shutdownPort?: number | null,+};++export type TomcatInstallation = TomcatInstallation_Serialize | TomcatInstallation_Deserialize;++export type TomcatInstallation_Deserialize = {+ path: string,+ version: string,+ libraries?: string[],+ name?: string | null,+ base?: string | null,+ tomee?: boolean,+};++export type TomcatInstallation_Serialize = {+ path: string,version: string,+ libraries: string[],+ name?: string | null,+ base?: string | null,+ tomee: boolean,};/** UI-facing state of one tool. */diff --git a/src/features/run/ConfigForm.tsx b/src/features/run/ConfigForm.tsxindex e684aa1df..1c4fb15d9 100644--- a/src/features/run/ConfigForm.tsx+++ b/src/features/run/ConfigForm.tsx@@ -363,8 +363,8 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi</div>)}{!template && (- <div className={styles.formHeader}>- <Field label="Name" error={errors.name}>+ <div className={clsx(styles.formHeader, config.kind === "tomcat" && styles.formHeaderTomcat)}>+ <Field label={config.kind === "tomcat" ? "Name:" : "Name"} error={errors.name}><Inputvalue={config.name}invalid={!!errors.name}@@ -372,341 +372,351 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modionChange={(e) => update({ name: e.target.value })}/></Field>- <Checkbox- checked={!config.local}- onChange={(shared) => update({ local: !shared })}- label="Store as project file"- aria-label="Store as project file (.openidea/run.toml); otherwise in the workspace (.openidea/run.local.toml)"- />+ <div className={styles.storeProjectGroup}>+ <Checkbox+ checked={!config.local}+ onChange={(shared) => update({ local: !shared })}+ label="Store as project file"+ aria-label="Store as project file (.openidea/run.toml); otherwise in the workspace (.openidea/run.local.toml)"+ />+ </div></div>)}- {!noProcess && (- <Field- label="Run on"- hint={- config.target- ? "Debugging is not available on run targets."- : runTargets.length- ? undefined- : "Add SSH hosts in Settings › Build, Execution, Deployment › Run Targets."- }- >- <Select- value={config.target ?? ""}- options={targetOptions}- onChange={(target) => onChange(withTarget(config, target))}- aria-label="Run on"- />- </Field>- )}- <div className={styles.formSection}>- <span className={styles.formSectionTitle}>{tx(kindLabel(config.kind))}</span>- <button- ref={modifyRef}- type="button"- className={styles.noticeLink}- aria-haspopup="menu"- aria-expanded={modifyOpen}- onClick={() => setModifyOpen((v) => !v)}- >- <T>Modify options</T> <Icon name="chevron-down" size={12} />- </button>- <span className={styles.chooserMuted}>⌥M</span>- <Menu- open={modifyOpen}- anchor={modifyRef}- items={menuItems}- placement="bottom-end"- onClose={() => setModifyOpen(false)}- />- </div>-- {config.kind === "tomcat" && <TomcatSettings config={config} onChange={onChange} />}-- {compound ? (- template ? null : (- <CompoundMembers- config={config}- all={all}- error={errors.compound}- onChange={(compound) => update({ compound })}- />- )- ) : params && type ? (- type.fields- .filter((f) => f.visible?.(params) ?? true)- .map((f) => (+ {config.kind === "tomcat" ? (+ <TomcatSettings config={config} onChange={onChange} />+ ) : (+ <>+ {!noProcess && (<Field- key={f.key}- label={f.label}- error={errors[f.key]}- hint={f.hint}- top={f.control === "textarea" || f.control === "output"}+ label="Run on"+ hint={+ config.target+ ? "Debugging is not available on run targets."+ : runTargets.length+ ? undefined+ : "Add SSH hosts in Settings › Build, Execution, Deployment › Run Targets."+ }>- <TypeField- field={f}- value={params[f.key] ?? ""}- params={params}- all={all}- invalid={!!errors[f.key]}- onChange={(v) => setParam(f.key, v)}+ <Select+ value={config.target ?? ""}+ options={targetOptions}+ onChange={(target) => onChange(withTarget(config, target))}+ aria-label="Run on"/></Field>- ))- ) : (- <>- {type && (- <div className={styles.notice}>- <T>This command line doesn't fit the type's form; it is edited as a command.</T>- </div>)}- <Field label="Command" error={errors.command}>- <Input- mono- value={config.command}- invalid={!!errors.command}- aria-label="Command"- placeholder="e.g. ./gradlew or cargo"- onChange={(e) => update({ command: e.target.value, params: {} })}- />- </Field>- <Field label="Arguments">- <Input- mono- aria-label="Arguments"- value={argsText ?? formatArgs(config.args)}- placeholder="Space separated; quote with ' or ""- onChange={(e) => {- setArgsText(e.target.value);- const args = parseArgs(e.target.value);- const module =- parseJavaArgs(args).mainClass === parseJavaArgs(config.args).mainClass ? config.module : undefined;- update({ args, params: {}, module });- }}+ <div className={styles.formSection}>+ <span className={styles.formSectionTitle}>{tx(kindLabel(config.kind))}</span>+ <button+ ref={modifyRef}+ type="button"+ className={styles.noticeLink}+ aria-haspopup="menu"+ aria-expanded={modifyOpen}+ onClick={() => setModifyOpen((v) => !v)}+ >+ <T>Modify options</T> <Icon name="chevron-down" size={12} />+ </button>+ <span className={styles.chooserMuted}>⌥M</span>+ <Menu+ open={modifyOpen}+ anchor={modifyRef}+ items={menuItems}+ placement="bottom-end"+ onClose={() => setModifyOpen(false)}/>- </Field>- </>- )}+ </div>- {!noProcess && (- <>- {!type?.ownsWorkingDirectory && (- <Field label="Working directory" error={errors.cwd}>- <div className={styles.inputWithButton}>- <Input- mono- aria-label="Working directory"- value={config.cwd ?? ""}- placeholder="Project root"- onChange={(e) => update({ cwd: e.target.value.trim() ? e.target.value : null })}- />- <BrowseButton- directory- title="Browse…"- from={root}- onPick={(path) => update({ cwd: projectRelative(root, path) || null })}- />- </div>- </Field>- )}- <Field- label="Environment variables"- error={errors.env}- hint="Separate variables with semicolon: VAR=value; VAR1=value1"- >- <div className={styles.inputWithButton}>- <Input- mono- aria-label="Environment variables"- value={envText ?? formatEnv(config.env)}- invalid={!!errors.env}- onChange={(e) => {- setEnvText(e.target.value);- update({ env: Object.fromEntries(parseEnv(e.target.value).map((r) => [r.key, r.value])) });- }}- onBlur={() => setEnvText(null)}- />- <IconButton- icon="list"- size="small"- iconSize={14}- title="Edit Environment Variables"- onClick={() => setEnvOpen(true)}+ {compound ? (+ template ? null : (+ <CompoundMembers+ config={config}+ all={all}+ error={errors.compound}+ onChange={(compound) => update({ compound })}/>- {isTauri() && !isRemoteWindow() && (- <IconButton- icon="folder-open"- size="small"- iconSize={14}- title="Browse for .env Files"- onClick={() =>- void choosePaths({ multiple: true, from: root }).then((picked) => {- const current = config.envFiles ?? [];- const added = picked.map((p) => projectRelative(root, p)).filter((f) => !current.includes(f));- if (added.length) update({ envFiles: [...current, ...added] });- })- }- />+ )+ ) : params && type ? (+ type.fields+ .filter((f) => f.visible?.(params) ?? true)+ .map((f) => (+ <Field+ key={f.key}+ label={f.label}+ error={errors[f.key]}+ hint={f.hint}+ top={f.control === "textarea" || f.control === "output"}+ >+ <TypeField+ field={f}+ value={params[f.key] ?? ""}+ params={params}+ all={all}+ invalid={!!errors[f.key]}+ onChange={(v) => setParam(f.key, v)}+ />+ </Field>+ ))+ ) : (+ <>+ {type && (+ <div className={styles.notice}>+ <T>This command line doesn't fit the type's form; it is edited as a command.</T>+ </div>)}- </div>- {config.includeSystemEnv === false && (- <span className={styles.chooserMuted}>- <T>System environment variables are not passed</T>- </span>- )}- </Field>- {isShown("envFiles") && (- <Field label='Paths to ".env" files' hint="Relative to the project root; separate with semicolon">- <Input- mono- aria-label='Paths to ".env" files'- value={envFilesText ?? (config.envFiles ?? []).join(";")}- placeholder=".env"- onChange={(e) => {- setEnvFilesText(e.target.value);- update({- envFiles: e.target.value- .split(";")- .map((p) => p.trim())- .filter(Boolean),- });- }}- onBlur={() => setEnvFilesText(null)}- />- </Field>- )}- {isShown("stdinFile") && (- <Field label="Redirect input from">- <div className={styles.inputWithButton}>+ <Field label="Command" error={errors.command}><Inputmono- aria-label="Redirect input from"- value={config.stdinFile ?? ""}- placeholder="File relative to the project root"- onChange={(e) => update({ stdinFile: e.target.value || null })}+ value={config.command}+ invalid={!!errors.command}+ aria-label="Command"+ placeholder="e.g. ./gradlew or cargo"+ onChange={(e) => update({ command: e.target.value, params: {} })}/>- <BrowseButton- title="Browse…"- from={root}- onPick={(path) => update({ stdinFile: projectRelative(root, path) || null })}+ </Field>+ <Field label="Arguments">+ <Input+ mono+ aria-label="Arguments"+ value={argsText ?? formatArgs(config.args)}+ placeholder="Space separated; quote with ' or ""+ onChange={(e) => {+ setArgsText(e.target.value);+ const args = parseArgs(e.target.value);+ const module =+ parseJavaArgs(args).mainClass === parseJavaArgs(config.args).mainClass+ ? config.module+ : undefined;+ update({ args, params: {}, module });+ }}/>- </div>- </Field>+ </Field>+ </>)}- {isShown("outputFile") && (- <Field label="Save console output to file">- <Input- mono- aria-label="Save console output to file"- value={config.outputFile ?? ""}- placeholder="File relative to the project root"- onChange={(e) => update({ outputFile: e.target.value || null })}- />- </Field>- )}- <Field label="Debug adapter">- <Select- value={config.debugAdapter ?? ""}- options={adapterOptions}- onChange={(v) => update({ debugAdapter: v || null })}- aria-label="Debug adapter"- />- </Field>- </>- )}- {isShown("beforeLaunch") && (- <Field label="Before launch" error={errors.beforeLaunch} top>- <div className={styles.taskList} role="list" aria-label={tx("Before launch tasks")}>- {tasks.map((t, i) => (- <div key={i} role="listitem" className={styles.taskRow}>- {t.kind === "command" ? (+ {!noProcess && (+ <>+ {!type?.ownsWorkingDirectory && (+ <Field label="Working directory" error={errors.cwd}>+ <div className={styles.inputWithButton}>+ <Input+ mono+ aria-label="Working directory"+ value={config.cwd ?? ""}+ placeholder="Project root"+ onChange={(e) => update({ cwd: e.target.value.trim() ? e.target.value : null })}+ />+ <BrowseButton+ directory+ title="Browse…"+ from={root}+ onPick={(path) => update({ cwd: projectRelative(root, path) || null })}+ />+ </div>+ </Field>+ )}+ <Field+ label="Environment variables"+ error={errors.env}+ hint="Separate variables with semicolon: VAR=value; VAR1=value1"+ >+ <div className={styles.inputWithButton}><Inputmono- aria-label={txTemplate(`Before launch command ${i + 1}`)}- value={t.target ?? ""}- placeholder="Shell command, e.g. make generate"- onChange={(e) => setTasks(tasks.map((x, j) => (j === i ? { ...x, target: e.target.value } : x)))}+ aria-label="Environment variables"+ value={envText ?? formatEnv(config.env)}+ invalid={!!errors.env}+ onChange={(e) => {+ setEnvText(e.target.value);+ update({ env: Object.fromEntries(parseEnv(e.target.value).map((r) => [r.key, r.value])) });+ }}+ onBlur={() => setEnvText(null)}+ />+ <IconButton+ icon="list"+ size="small"+ iconSize={14}+ title="Edit Environment Variables"+ onClick={() => setEnvOpen(true)}/>- ) : (- <span className={styles.taskLabel}>{txTemplate(taskLabel(t, all))}</span>+ {isTauri() && !isRemoteWindow() && (+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={14}+ title="Browse for .env Files"+ onClick={() =>+ void choosePaths({ multiple: true, from: root }).then((picked) => {+ const current = config.envFiles ?? [];+ const added = picked.map((p) => projectRelative(root, p)).filter((f) => !current.includes(f));+ if (added.length) update({ envFiles: [...current, ...added] });+ })+ }+ />+ )}+ </div>+ {config.includeSystemEnv === false && (+ <span className={styles.chooserMuted}>+ <T>System environment variables are not passed</T>+ </span>)}- <IconButton- icon="arrow-up"- size="small"- iconSize={12}- title="Move Up"- disabled={i === 0}- onClick={() => moveTask(i, -1)}- />- <IconButton- icon="arrow-down"- size="small"- iconSize={12}- title="Move Down"- disabled={i === tasks.length - 1}- onClick={() => moveTask(i, 1)}+ </Field>+ {isShown("envFiles") && (+ <Field label='Paths to ".env" files' hint="Relative to the project root; separate with semicolon">+ <Input+ mono+ aria-label='Paths to ".env" files'+ value={envFilesText ?? (config.envFiles ?? []).join(";")}+ placeholder=".env"+ onChange={(e) => {+ setEnvFilesText(e.target.value);+ update({+ envFiles: e.target.value+ .split(";")+ .map((p) => p.trim())+ .filter(Boolean),+ });+ }}+ onBlur={() => setEnvFilesText(null)}+ />+ </Field>+ )}+ {isShown("stdinFile") && (+ <Field label="Redirect input from">+ <div className={styles.inputWithButton}>+ <Input+ mono+ aria-label="Redirect input from"+ value={config.stdinFile ?? ""}+ placeholder="File relative to the project root"+ onChange={(e) => update({ stdinFile: e.target.value || null })}+ />+ <BrowseButton+ title="Browse…"+ from={root}+ onPick={(path) => update({ stdinFile: projectRelative(root, path) || null })}+ />+ </div>+ </Field>+ )}+ {isShown("outputFile") && (+ <Field label="Save console output to file">+ <Input+ mono+ aria-label="Save console output to file"+ value={config.outputFile ?? ""}+ placeholder="File relative to the project root"+ onChange={(e) => update({ outputFile: e.target.value || null })}+ />+ </Field>+ )}+ <Field label="Debug adapter">+ <Select+ value={config.debugAdapter ?? ""}+ options={adapterOptions}+ onChange={(v) => update({ debugAdapter: v || null })}+ aria-label="Debug adapter"/>- <IconButton- icon="minus"+ </Field>+ </>+ )}++ {isShown("beforeLaunch") && (+ <Field label="Before launch" error={errors.beforeLaunch} top>+ <div className={styles.taskList} role="list" aria-label={tx("Before launch tasks")}>+ {tasks.map((t, i) => (+ <div key={i} role="listitem" className={styles.taskRow}>+ {t.kind === "command" ? (+ <Input+ mono+ aria-label={txTemplate(`Before launch command ${i + 1}`)}+ value={t.target ?? ""}+ placeholder="Shell command, e.g. make generate"+ onChange={(e) =>+ setTasks(tasks.map((x, j) => (j === i ? { ...x, target: e.target.value } : x)))+ }+ />+ ) : (+ <span className={styles.taskLabel}>{txTemplate(taskLabel(t, all))}</span>+ )}+ <IconButton+ icon="arrow-up"+ size="small"+ iconSize={12}+ title="Move Up"+ disabled={i === 0}+ onClick={() => moveTask(i, -1)}+ />+ <IconButton+ icon="arrow-down"+ size="small"+ iconSize={12}+ title="Move Down"+ disabled={i === tasks.length - 1}+ onClick={() => moveTask(i, 1)}+ />+ <IconButton+ icon="minus"+ size="small"+ iconSize={12}+ title="Remove Task"+ onClick={() => setTasks(tasks.filter((_, j) => j !== i))}+ />+ </div>+ ))}+ <Button+ ref={taskRef}size="small"- iconSize={12}- title="Remove Task"- onClick={() => setTasks(tasks.filter((_, j) => j !== i))}- />+ variant="ghost"+ icon="plus"+ aria-haspopup="menu"+ onClick={() => setTaskMenu(true)}+ >+ <T>Add task</T>+ </Button>+ <Menu open={taskMenu} anchor={taskRef} items={taskItems} onClose={() => setTaskMenu(false)} /></div>- ))}- <Button- ref={taskRef}- size="small"- variant="ghost"- icon="plus"- aria-haspopup="menu"- onClick={() => setTaskMenu(true)}- >- <T>Add task</T>- </Button>- <Menu open={taskMenu} anchor={taskRef} items={taskItems} onClose={() => setTaskMenu(false)} />- </div>- </Field>- )}+ </Field>+ )}- {chips.length > 0 && (- <div className={styles.chips}>- {chips.map((id) => (- <span key={id} className={styles.chip}>- <T>{OPTION_LABELS[id]}</T>- <IconButton- icon="close"- size="small"- iconSize={10}- title={tx`Remove '${OPTION_LABELS[id]}'`}- onClick={() => update(optionPatch(id, false))}- />- </span>- ))}- </div>- )}+ {chips.length > 0 && (+ <div className={styles.chips}>+ {chips.map((id) => (+ <span key={id} className={styles.chip}>+ <T>{OPTION_LABELS[id]}</T>+ <IconButton+ icon="close"+ size="small"+ iconSize={10}+ title={tx`Remove '${OPTION_LABELS[id]}'`}+ onClick={() => update(optionPatch(id, false))}+ />+ </span>+ ))}+ </div>+ )}- {!noProcess && !template && (- <div className={styles.editPreview}>- <span className={styles.chooserMuted}>- <T>Command line</T>- </span>- <code>{commandLine(config) || "—"}</code>- </div>- )}+ {!noProcess && !template && (+ <div className={styles.editPreview}>+ <span className={styles.chooserMuted}>+ <T>Command line</T>+ </span>+ <code>{commandLine(config) || "—"}</code>+ </div>+ )}- {envOpen && (- <EnvDialog- env={config.env}- includeSystemEnv={config.includeSystemEnv !== false}- onClose={() => setEnvOpen(false)}- onOk={(env, includeSystemEnv) => {- setEnvText(null);- update({ env, includeSystemEnv });- }}- />+ {envOpen && (+ <EnvDialog+ env={config.env}+ includeSystemEnv={config.includeSystemEnv !== false}+ onClose={() => setEnvOpen(false)}+ onOk={(env, includeSystemEnv) => {+ setEnvText(null);+ update({ env, includeSystemEnv });+ }}+ />+ )}+ </>)}</>);diff --git a/src/features/run/EditConfigsDialog.tsx b/src/features/run/EditConfigsDialog.tsxindex 79c2736c0..965c6de2f 100644--- a/src/features/run/EditConfigsDialog.tsx+++ b/src/features/run/EditConfigsDialog.tsx@@ -530,6 +530,12 @@ function EditConfigsDialog() {);}const c = r.config;+ const isTomcat = c.kind === "tomcat";+ const tomcatNoArtifact =+ isTomcat &&+ ((c.params?.deployment ?? "artifact") === "artifact"+ ? !c.params?.artifact+ : !c.params?.deploymentPath?.trim());return (<buttonkey={r.key}@@ -546,15 +552,22 @@ function EditConfigsDialog() {e.dataTransfer.effectAllowed = "move";}}>- <Icon- name={configIcon(c)}- size={13}- className={clsx(styles.chooserIcon, temporary.includes(c.id) && styles.chooserTemporary)}- />+ <span className={styles.tomcatTreeIconWrap}>+ <Icon+ name={configIcon(c)}+ size={13}+ className={clsx(styles.chooserIcon, temporary.includes(c.id) && styles.chooserTemporary)}+ />+ {tomcatNoArtifact && (+ <Icon name="close" size={9} className={styles.tomcatTreeErrorBadge} label="Invalid" />+ )}+ </span><span className={styles.chooserName}>{c.name || <T>Unnamed</T>}</span>{c.target && <span className={styles.chooserMuted}>@ {targetName(c, runTargets)}</span>}{errorsById[c.id] && <Icon name="error" size={12} className={styles.failed} label="Invalid" />}- {!c.detected && <span className={styles.chooserMuted}>{c.local ? "local" : "user"}</span>}+ {!c.detected && !isTomcat && (+ <span className={styles.chooserMuted}>{c.local ? "local" : "user"}</span>+ )}</button>);})}@@ -631,7 +644,9 @@ function EditConfigsDialog() {</>)}</div>- <div className={styles.editForm}>+ <div+ className={clsx(styles.editForm, mode === "configs" && current?.kind === "tomcat" && styles.editFormTomcat)}+ >{mode === "templates" ? (currentTemplate ? (<>diff --git a/src/features/run/Run.module.css b/src/features/run/Run.module.cssindex 890faec31..aff76271c 100644--- a/src/features/run/Run.module.css+++ b/src/features/run/Run.module.css@@ -482,6 +482,31 @@flex-direction: column;gap: 8px;}+.editFormTomcat {+ overflow: hidden;+}+.tomcatTreeIconWrap {+ position: relative;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex: none;+}+.tomcatTreeErrorBadge {+ position: absolute;+ right: -3px;+ bottom: -3px;+ width: 9px;+ height: 9px;+ border-radius: 50%;+ background: var(--danger);+ color: var(--fg-on-accent, white);+ font-size: 8px;+ font-weight: 700;+ line-height: 9px;+ text-align: center;+ pointer-events: none;+}.editForm > .notice {border: 1px solid var(--border-popup);border-radius: var(--radius-small);@@ -549,6 +574,21 @@padding-bottom: 10px;border-bottom: 1px solid var(--border-popup);}+.formHeaderTomcat {+ padding-bottom: 4px;+ border-bottom: none;+ flex: none;+}+.formHeaderTomcat .field {+ grid-template-columns: auto 1fr;+ gap: 10px;+ max-width: 440px;+}+.storeProjectGroup {+ display: inline-flex;+ align-items: center;+ gap: 6px;+}.formSection {display: flex;align-items: center;@@ -567,10 +607,15 @@.inputWithButton {display: flex;align-items: center;- gap: 4px;+ gap: 6px;+ min-width: 0;}.inputWithButton > :first-child {flex: 1;+ min-width: 0;+}+.inputWithButton > button {+ flex-shrink: 0;}.textarea {min-height: 72px;@@ -808,3 +853,475 @@padding: 4px 0 0 8px;background: var(--bg-island);}++/* Tomcat Server configuration tabs, sections, and Application Servers dialog */+.srOnly {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}+.tomcatContainer {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+}+.tomcatTabs {+ flex: none;+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 2px 0 8px;+ border-bottom: 1px solid var(--border-popup);+ margin-bottom: 6px;+}+.tomcatScrollArea {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding-right: 4px;+ padding-bottom: 8px;+}+.tomcatFormRow {+ display: grid;+ grid-template-columns: 126px 1fr;+ align-items: center;+ gap: 10px;+}+.tomcatRowLabel {+ color: var(--fg-secondary);+ font-size: var(--fs-ui);+ white-space: normal;+}+.tomcatSection {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin-top: 2px;+}+.tomcatSectionHeader {+ display: flex;+ align-items: center;+ gap: 8px;+ color: var(--fg-secondary);+ font-size: var(--fs-ui);+ font-weight: 500;+}+.tomcatSectionLine {+ flex: 1;+ height: 1px;+ background: var(--border-popup);+}+.tomcatOpenBrowserControls {+ display: flex;+ align-items: center;+ flex-wrap: nowrap;+ gap: 8px;+ padding-left: 14px;+}+.tomcatBrowserSelect {+ width: 124px;+ flex: none;+}+.tomcatDotsBtn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 26px;+ height: var(--h-control, 24px);+ padding: 0;+ border-radius: var(--radius-control, 4px);+ background: var(--bg-button);+ box-shadow: inset 0 0 0 1px var(--border-button);+ color: var(--fg);+ font-size: var(--fs-ui);+ cursor: pointer;+ flex: none;+}+.tomcatDotsBtn:hover {+ background: var(--bg-hover);+}+.tomcatUrlRow {+ display: grid;+ grid-template-columns: 40px 1fr;+ align-items: center;+ gap: 8px;+ padding-left: 34px;+}+.tomcatUrlLabel {+ color: var(--fg-secondary);+ font-size: var(--fs-ui);+}+.tomcatInputInside {+ position: relative;+ display: flex;+ align-items: center;+ flex: 1;+ min-width: 0;+}+.tomcatInputInside > input {+ flex: 1;+ min-width: 0;+ padding-right: 28px;+}+.tomcatInputInside:has(.tomcatInlineChevronBtn) > input {+ padding-right: 52px;+}+.tomcatInlineIconBtn {+ position: absolute;+ right: 3px;+ width: 20px;+ height: 20px;+ color: var(--fg-subtle);+}+.tomcatInputInside:has(.tomcatInlineChevronBtn) .tomcatInlineIconBtn {+ right: 25px;+}+.tomcatInlineChevronBtn {+ position: absolute;+ right: 3px;+ width: 20px;+ height: 20px;+ color: var(--fg-subtle);+ border-left: 1px solid var(--border-button);+ border-radius: 0 var(--radius-control, 4px) var(--radius-control, 4px) 0;+}+.tomcatDivider {+ flex: none;+ height: 1px;+ background: var(--border-popup);+ margin: 2px 0;+}+.tomcatUpdateRow {+ display: flex;+ align-items: center;+ gap: 14px;+}+.tomcatUpdateSelect {+ width: 164px;+ max-width: 100%;+}+.tomcatServerSettingsGrid {+ display: grid;+ grid-template-columns: minmax(220px, 260px) 1fr;+ gap: 16px 24px;+ align-items: start;+ padding-left: 14px;+}+.tomcatPortsCol {+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.tomcatPortField {+ display: grid;+ grid-template-columns: 90px 1fr;+ align-items: center;+ gap: 8px;+}+.tomcatFlagsCol {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding-top: 2px;+}+.tomcatWarningBar {+ flex: none;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 8px 4px 2px;+ margin-top: 4px;+ border-top: 1px solid var(--border-popup);+ background: transparent;+}+.tomcatWarningText {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ color: var(--warning, var(--fg-strong));+ font-size: var(--fs-ui);+ font-weight: 500;+}+.appServersBody {+ display: flex;+ min-height: 360px;+ max-height: 480px;+}+.appServersSidebar {+ width: 200px;+ flex: none;+ display: flex;+ flex-direction: column;+ border-right: 1px solid var(--border-popup);+}+.appServersToolbar {+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 4px 6px;+ border-bottom: 1px solid var(--border-popup);+}+.appServersToolbarPlain {+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 2px 0;+}+.appServersList {+ flex: 1;+ overflow: auto;+ padding: 4px 0;+}+.appServersDetail {+ flex: 1;+ min-width: 0;+ overflow: auto;+ padding: 12px 16px;+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.appServerFieldRow {+ display: grid;+ grid-template-columns: 145px 1fr;+ align-items: center;+ gap: 10px;+}+.appServerFieldLabel {+ color: var(--fg-secondary);+ font-size: var(--fs-ui);+ white-space: nowrap;+}+.appServersLibs {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-height: 140px;+ border: 1px solid var(--border-popup);+ border-radius: var(--radius-small);+}+.appServersLibTree {+ flex: 1;+ overflow: auto;+ padding: 4px 0;+}+.appServersLibHeader {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 2px 8px;+ font-size: var(--fs-ui);+ color: var(--fg-secondary);+}+.appServersLibRow {+ display: flex;+ align-items: center;+ gap: 6px;+ width: 100%;+ padding: 2px 8px 2px 24px;+ font-family: var(--font-mono);+ font-size: var(--fs-small);+ color: var(--fg);+ text-align: left;+}+.appServersLibRow:hover {+ background: var(--bg-hover);+}+.appServersLibRowSelected,+.appServersLibRowSelected:hover {+ background: var(--bg-selected-strong);+ color: var(--fg-strong);+}+.tomcatBoxPanel {+ display: flex;+ flex-direction: column;+ min-height: 120px;+ border: 1px solid var(--border-popup);+ border-radius: var(--radius-small);+}+.tomcatDeployPanel {+ min-height: 220px;+}+.tomcatLogsPanel {+ min-height: 185px;+}+.tomcatCoveragePanel {+ min-height: 110px;+}+.tomcatEnvPanel {+ min-height: 130px;+}+.tomcatBoxSmall {+ min-height: 76px;+}+.tomcatBoxEmpty {+ flex: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 24px 12px;+ color: var(--fg-subtle);+ font-size: var(--fs-ui);+}+.tomcatPlainLabel {+ color: var(--fg-secondary);+ font-size: var(--fs-ui);+}+.tomcatSaveLogRow {+ display: grid;+ grid-template-columns: auto 1fr;+ align-items: center;+ gap: 10px;+}+.tomcatLogHeader,+.tomcatLogRow {+ display: grid;+ grid-template-columns: 72px 1fr 90px;+ align-items: center;+ gap: 8px;+ min-height: var(--h-row);+ padding: 0 10px;+ font-size: var(--fs-ui);+}+.tomcatLogHeader {+ color: var(--fg-subtle);+ font-size: var(--fs-small);+ border-bottom: 1px solid var(--border-popup);+}+.tomcatLogRow {+ cursor: pointer;+}+.tomcatLogRow:hover {+ background: var(--bg-hover);+}+.tomcatLogRowSelected,+.tomcatLogRowSelected:hover {+ background: var(--bg-selected-strong);+ color: var(--fg-strong);+}+.tomcatLogCheckCell {+ display: flex;+ align-items: center;+ justify-content: center;+}+.tomcatEnvHeader,+.tomcatEnvRow {+ display: grid;+ grid-template-columns: 1fr 2fr;+ align-items: center;+ gap: 8px;+ min-height: var(--h-row);+ padding: 0 10px;+ font-size: var(--fs-ui);+}+.tomcatEnvHeader {+ color: var(--fg-subtle);+ font-size: var(--fs-small);+ border-bottom: 1px solid var(--border-popup);+}+.tomcatEnvRow:hover {+ background: var(--bg-hover);+}+.tomcatEnvRowSelected,+.tomcatEnvRowSelected:hover {+ background: var(--bg-selected-strong);+ color: var(--fg-strong);+}+.tomcatRunnerList {+ display: flex;+ flex-direction: column;+ border: 1px solid var(--border-popup);+ border-radius: var(--radius-small);+ padding: 2px 0;+}+.tomcatScriptRow {+ display: grid;+ grid-template-columns: 1fr auto;+ align-items: center;+ gap: 10px;+}+.tomcatDebugConnectionSection {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin-top: 2px;+}+.tomcatDebugTransportRow {+ display: flex;+ align-items: center;+ gap: 16px;+}+.tomcatDebugPortRow {+ display: flex;+ align-items: center;+ gap: 10px;+}+.tomcatDebugLabel {+ width: 72px;+ color: var(--fg-secondary);+ font-size: var(--fs-ui);+ flex: none;+}+.tomcatRadioLabel {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ color: var(--fg-subtle);+ font-size: var(--fs-ui);+}+.tomcatDebugPortInput {+ width: 110px;+}+.tomcatDebugSettingsBtnWrap {+ margin-left: auto;+}+.tomcatBeforeLaunchFooter {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 16px;+ margin-top: 4px;+}+.tomcatSectionToggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ color: var(--fg-secondary);+ font-size: var(--fs-ui);+ font-weight: 500;+ cursor: pointer;+}+.addServerDialogBody {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 14px 16px;+}+.addServerFieldRow {+ display: grid;+ grid-template-columns: 145px 1fr;+ align-items: center;+ gap: 10px;+}+.addServerErrorRow {+ display: flex;+ align-items: center;+ gap: 8px;+ color: var(--fg);+ font-size: var(--fs-ui);+}+.addServerErrorIcon {+ color: var(--danger);+ flex: none;+}diff --git a/src/features/run/TomcatSettings.tsx b/src/features/run/TomcatSettings.tsxindex 92c02c326..3b93aa63a 100644--- a/src/features/run/TomcatSettings.tsx+++ b/src/features/run/TomcatSettings.tsx@@ -1,39 +1,185 @@import { useEffect, useRef, useState } from "react";-import { call, commands, type RunConfig, type WebArtifact } from "@/platform/ipc";-import { Select, T } from "@/ui";+import clsx from "clsx";+import { call, commands, isTauri, type RunConfig, type TomcatInstallation, type WebArtifact } from "@/platform/ipc";+import { usePlatform } from "@/platform/platformInfo";+import { useWorkflowSettings } from "@/platform/workflowSettings";+import { isRemoteWindow } from "@/platform/remote";+import { Button, Checkbox, Dialog, Icon, IconButton, Input, Menu, Select, Tabs, T, type MenuItem } from "@/ui";import { useTx } from "@/platform/i18n";+import { tomcatBrowserUrl } from "./tomcat";import styles from "./Run.module.css";-/** Asynchronous installation validation and project artifact discovery in the configuration editor. */+type TomcatTab = "server" | "deployment" | "logs" | "startup";+type StartupRunnerId = "run" | "debug";++interface TomcatServerProfile {+ id: string;+ name: string;+ home: string;+ base: string;+ version: string;+ libraries: string[];+ tomee?: boolean;+}++const SERVERS_STORAGE_KEY = "openidea.tomcat.servers.v1";++function shortVersion(version: string): string {+ return version.replace(/^Apache Tomcat\//i, "").trim() || version;+}++function defaultServerName(home: string, version: string): string {+ const short = shortVersion(version);+ if (short && short !== "Apache Tomcat") return `Tomcat ${short}`;+ const base = home.replace(/\\/g, "/").replace(/\/+$/, "").split("/").pop();+ return base || "Tomcat";+}++function loadSavedServers(): TomcatServerProfile[] {+ try {+ const raw = localStorage.getItem(SERVERS_STORAGE_KEY);+ if (!raw) return [];+ const parsed = JSON.parse(raw);+ if (!Array.isArray(parsed)) return [];+ return parsed.filter(+ (x): x is TomcatServerProfile =>+ x &&+ typeof x.id === "string" &&+ typeof x.name === "string" &&+ typeof x.home === "string" &&+ typeof x.base === "string" &&+ typeof x.version === "string" &&+ Array.isArray(x.libraries) &&+ x.libraries.every((library: unknown) => typeof library === "string"),+ );+ } catch {+ return [];+ }+}++function saveServersToStorage(servers: TomcatServerProfile[]): void {+ try {+ localStorage.setItem(SERVERS_STORAGE_KEY, JSON.stringify(servers));+ } catch {+ // ignore storage errors+ }+}++function serializeEnvPairs(rows: ReadonlyArray<{ name: string; value: string }>): string {+ return rows.map((r) => `${r.name}=${r.value}`).join("\n");+}++async function pickLocalPath(directory: boolean, defaultPath?: string): Promise<string | null> {+ if (!isTauri() || isRemoteWindow()) return null;+ const { open } = await import("@tauri-apps/plugin-dialog");+ const picked = await open({ directory, multiple: false, defaultPath: defaultPath || undefined });+ return typeof picked === "string" ? picked : Array.isArray(picked) ? (picked[0] ?? null) : null;+}++/** Local installation validation, server profiles, and WAR artifact discovery. */export function TomcatSettings({ config, onChange }: { config: RunConfig; onChange: (config: RunConfig) => void }) {const tx = useTx();+ const windows = usePlatform((state) => state.os === "windows");+ const openByDefault = useWorkflowSettings((settings) => settings.run.showOnStart);+ const [activeTab, setActiveTab] = useState<TomcatTab>("server");+ const [installations, setInstallations] = useState<TomcatInstallation[]>([]);+ const [savedServers, setSavedServers] = useState<TomcatServerProfile[]>(() => loadSavedServers());+ const [appServersOpen, setAppServersOpen] = useState(false);+ const [vmDialogOpen, setVmDialogOpen] = useState(false);+ const [deployMenuOpen, setDeployMenuOpen] = useState(false);+ const [jreMenuOpen, setJreMenuOpen] = useState(false);+ const [detectedJdks, setDetectedJdks] = useState<Array<{ label: string; path: string }>>([]);const [artifacts, setArtifacts] = useState<WebArtifact[]>([]);const [status, setStatus] = useState("");const [error, setError] = useState("");+ const [startupRunner, setStartupRunner] = useState<StartupRunnerId>("run");+ const [selectedEnvIdx, setSelectedEnvIdx] = useState<number>(0);+ const [beforeLaunchOpen, setBeforeLaunchOpen] = useState(true);+ const deployAddRef = useRef<HTMLButtonElement>(null);+ const jreBtnRef = useRef<HTMLButtonElement>(null);const latest = useRef({ config, onChange });useEffect(() => {latest.current = { config, onChange };}, [config, onChange]);++ const publish = (next: RunConfig) => {+ const { onChange } = latest.current;+ latest.current = { config: next, onChange };+ onChange(next);+ };++ const setParams = (patch: Record<string, string>, nextName?: string) => {+ const { config } = latest.current;+ const nextParams = { ...(config.params ?? {}) };+ for (const [k, v] of Object.entries(patch)) {+ if (v || k === "startupEnvRun" || k === "startupEnvDebug") nextParams[k] = v;+ else delete nextParams[k];+ }+ publish({+ ...config,+ ...(nextName ? { name: nextName } : {}),+ params: nextParams,+ });+ };+const select = (artifact: WebArtifact) => {- const { config, onChange } = latest.current;- onChange({+ const { config } = latest.current;+ publish({...config,cwd: artifact.module || null,params: {...config.params,+ deployment: "artifact",artifact: artifact.id,artifactName: artifact.name,contextPath: config.params?.contextPath || `/${artifact.name}`,},});};+useEffect(() => {let live = true;+ if (commands.runTomcatInstallations) {+ void call(commands.runTomcatInstallations())+ .then((items) => {+ if (!live) return;+ setInstallations(items);+ const { config } = latest.current;+ if (!config.params?.tomcatHome && items[0]) {+ const first = items[0];+ const isDefaultUnnamed = config.name === "Unnamed" || /^Unnamed \(\d+\)$/.test(config.name);+ publish({+ ...config,+ ...(isDefaultUnnamed && first.name ? { name: first.name } : {}),+ params: {+ ...config.params,+ tomcatHome: first.path,+ ...(first.name ? { serverName: first.name } : {}),+ ...(first.base && first.base !== first.path ? { tomcatBase: first.base } : {}),+ },+ });+ }+ })+ .catch(() => {});+ }+ if (commands.sdkDetect) {+ void call(commands.sdkDetect("jdk"))+ .then((sdks) => {+ if (!live || !Array.isArray(sdks)) return;+ const jdks = sdks.map((s) => ({+ label: s.name || (s.version ? `${s.version} (${s.path})` : s.path),+ path: s.path,+ }));+ setDetectedJdks(jdks);+ })+ .catch(() => {});+ }void call(commands.runTomcatArtifacts()).then((items) => {if (!live) return;setArtifacts(items);- if (!latest.current.config.params?.artifact && items[0]) select(items[0]);+ const params = latest.current.config.params;+ if ((params?.deployment ?? "artifact") === "artifact" && !params?.artifact && items[0]) select(items[0]);}).catch((e) => {if (live) setError(String(e));@@ -42,6 +188,7 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChanlive = false;};}, []);+const home = config.params?.tomcatHome ?? "";useEffect(() => {let live = true;@@ -62,42 +209,1374 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChanclearTimeout(timer);};}, [home]);++ const allServers: TomcatServerProfile[] = [...savedServers];+ for (const inst of installations) {+ if (!allServers.some((s) => s.home === inst.path)) {+ allServers.push({+ id: `detected:${inst.path}`,+ name: inst.name || defaultServerName(inst.path, inst.version),+ home: inst.path,+ base: inst.base || inst.path,+ version: shortVersion(inst.version),+ libraries: inst.libraries ?? [],+ tomee: inst.tomee,+ });+ }+ }+ if (home.trim() && !allServers.some((s) => s.home === home)) {+ allServers.push({+ id: `current:${home}`,+ name: config.params?.serverName || defaultServerName(home, status),+ home,+ base: config.params?.tomcatBase || home,+ version: shortVersion(status),+ libraries: config.params?.tomcatLibraries ? config.params.tomcatLibraries.split(";").filter(Boolean) : [],+ });+ }++ const deploymentKind = config.params?.deployment ?? "artifact";+ const noArtifactConfigured =+ (deploymentKind === "artifact" && !config.params?.artifact) ||+ (deploymentKind !== "artifact" && !config.params?.deploymentPath?.trim());++ const useDefaultStartup = config.params?.useDefaultStartup !== "false";+ const useDefaultShutdown = config.params?.useDefaultShutdown !== "false";+ const defaultStartupCmd = home+ ? `${home.replace(/\/+$/, "")}/bin/${windows ? "catalina.bat" : "catalina.sh"} run`+ : "bin/catalina.sh run";+ const defaultShutdownCmd = home+ ? `${home.replace(/\/+$/, "")}/bin/${windows ? "catalina.bat" : "catalina.sh"} stop`+ : "bin/catalina.sh stop";++ const debugPort = config.params?.debugPort ?? "";+ const envParamKey = startupRunner === "debug" ? "startupEnvDebug" : "startupEnvRun";+ const rawEnvForRunner = config.params?.[envParamKey] ?? config.params?.startupEnv ?? "";+ const envRows = rawEnvForRunner+ .split("\n")+ .filter(Boolean)+ .map((line) => {+ const idx = line.indexOf("=");+ return idx >= 0 ? { name: line.slice(0, idx), value: line.slice(idx + 1) } : { name: line, value: "" };+ });+ const setEnvRows = (next: Array<{ name: string; value: string }>) => {+ setParams({ [envParamKey]: serializeEnvPairs(next) });+ };+ const defaultJrePlaceholder = tx("Project JDK");++ const jreMenuItems: MenuItem[] = [+ {+ label: defaultJrePlaceholder,+ verbatim: true,+ run: () => setParams({ jre: "" }),+ },+ ...detectedJdks.map((jdk): MenuItem => ({+ label: jdk.label,+ verbatim: true,+ run: () => setParams({ jre: jdk.path }),+ })),+ ];++ const deployMenuItems: MenuItem[] = [+ ...(artifacts.length > 0+ ? artifacts.map((a): MenuItem => {+ const itemLabel = [a.name, "war exploded"].join(":");+ return {+ label: itemLabel,+ verbatim: true,+ icon: "file-archive",+ run: () => select(a),+ };+ })+ : []),+ ...(["directory", "war"] as const).map((deployment): MenuItem => ({+ label: deployment === "war" ? "WAR file" : "Exploded directory",+ icon: "folder-open",+ run: () => {+ void pickLocalPath(deployment === "directory").then((picked) => {+ if (!picked) return;+ const name =+ picked+ .replace(/\\/g, "/")+ .replace(/\/+$/, "")+ .split("/")+ .pop()+ ?.replace(/\.war$/i, "") || "app";+ setParams({ deployment, deploymentPath: picked, contextPath: config.params?.contextPath || `/${name}` });+ });+ },+ })),+ ];+return (- <>+ <div className={styles.tomcatContainer}>+ <Tabs+ className={styles.tomcatTabs}+ variant="compact"+ aria-label="Tomcat configuration tabs"+ panelIdPrefix="tomcat-config"+ items={[+ { id: "server", label: "Server" },+ { id: "deployment", label: "Deployment" },+ { id: "logs", label: "Logs" },+ { id: "startup", label: "Startup/Connection" },+ ]}+ activeId={activeTab}+ onSelect={(id) => setActiveTab(id as TomcatTab)}+ />+{status && (- <div className={styles.notice} role="status">+ <span className={styles.srOnly} role="status">{status}- </div>+ </span>)}{error && (<div className={styles.fieldError} role="alert">{tx(error)}</div>)}- {(config.params?.deployment ?? "artifact") === "artifact" && (- <div className={styles.field}>- <span className={styles.fieldLabel}>- <T>WAR artifact</T>- </span>- <div className={styles.fieldControl}>- <Select- aria-label="WAR artifact"- value={config.params?.artifact || null}- placeholder="Choose a WAR module"- options={artifacts.map((a) => ({ value: a.id, label: `${a.name} (${a.tool}: ${a.module || "."})` }))}- onChange={(id) => {- const artifact = artifacts.find((a) => a.id === id);- if (artifact) select(artifact);- }}++ <div+ className={styles.tomcatScrollArea}+ role="tabpanel"+ id={`tomcat-config-panel-${activeTab}`}+ aria-labelledby={`tomcat-config-tab-${activeTab}`}+ >+ {activeTab === "server" && (+ <>+ <div className={styles.tomcatFormRow}>+ <span className={styles.tomcatRowLabel}>+ <T>Application server:</T>+ </span>+ <div className={styles.inputWithButton}>+ <Select+ aria-label="Application server"+ value={allServers.some((s) => s.home === home) ? home : null}+ placeholder="Choose a detected Tomcat installation"+ options={allServers.map((s) => ({+ value: s.home,+ label: s.name || s.home,+ }))}+ onChange={(selectedHome) => {+ if (!selectedHome) return;+ const srv = allServers.find((s) => s.home === selectedHome);+ const shouldRename =+ srv?.name &&+ (config.name === "Unnamed" ||+ /^Unnamed \(\d+\)$/.test(config.name) ||+ config.name === config.params?.serverName);+ setParams(+ {+ tomcatHome: selectedHome,+ serverName: srv?.name ?? "",+ tomcatBase: srv && srv.base !== srv.home ? srv.base : "",+ tomcatLibraries: srv?.libraries.length ? srv.libraries.join(";") : "",+ },+ shouldRename ? srv.name : undefined,+ );+ }}+ />+ <Button size="small" onClick={() => setAppServersOpen(true)}>+ <T>Configure...</T>+ </Button>+ </div>+ </div>++ <div className={styles.tomcatSection}>+ <div className={styles.tomcatSectionHeader}>+ <span>+ <T>Open browser</T>+ </span>+ <span className={styles.tomcatSectionLine} />+ </div>+ <div className={styles.tomcatOpenBrowserControls}>+ <Checkbox+ checked={config.params?.openBrowser === "true"}+ onChange={(on) => setParams({ openBrowser: on ? "true" : "false" })}+ label="After launch"+ />+ </div>+ <div className={styles.tomcatUrlRow}>+ <span className={styles.tomcatUrlLabel}>+ <T>URL:</T>+ </span>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="Browser URL"+ value={config.params?.browserUrl || tomcatBrowserUrl(config)}+ onChange={(e) => setParams({ browserUrl: e.target.value })}+ />+ </div>+ </div>+ </div>++ <div className={styles.tomcatDivider} />++ <div className={styles.tomcatFormRow}>+ <span className={styles.tomcatRowLabel}>+ <T>VM options:</T>+ </span>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="VM options"+ value={config.params?.vmOptions ?? ""}+ onChange={(e) => setParams({ vmOptions: e.target.value })}+ />+ <IconButton+ icon="expand-all"+ size="small"+ iconSize={13}+ title="Expand (⇧⏎)"+ className={styles.tomcatInlineIconBtn}+ onClick={() => setVmDialogOpen(true)}+ />+ </div>+ </div>++ <div className={styles.tomcatFormRow}>+ <span className={styles.tomcatRowLabel}>+ <T>On 'Update' action:</T>+ </span>+ <div className={styles.tomcatUpdateRow}>+ <div className={styles.tomcatUpdateSelect}>+ <Select+ aria-label="On 'Update' action"+ value={config.params?.onUpdate || "ask"}+ options={[+ { value: "restart", label: "Restart server" },+ { value: "redeploy", label: "Redeploy" },+ { value: "resources", label: "Update resources" },+ { value: "classes", label: "Update classes and resources" },+ { value: "ask", label: "Show chooser" },+ ]}+ onChange={(v) => setParams({ onUpdate: v })}+ />+ </div>+ </div>+ </div>++ {(!noArtifactConfigured || !!config.params?.onDeactivation) && (+ <div className={styles.tomcatFormRow}>+ <span className={styles.tomcatRowLabel}>+ <T>On frame deactivation:</T>+ </span>+ <div className={styles.tomcatUpdateSelect}>+ <Select+ aria-label="On frame deactivation"+ value={config.params?.onDeactivation || "none"}+ options={[+ { value: "none", label: "Do nothing" },+ { value: "resources", label: "Update resources" },+ { value: "classes", label: "Update classes and resources" },+ ]}+ onChange={(v) => setParams({ onDeactivation: v })}+ />+ </div>+ </div>+ )}++ <div className={styles.tomcatFormRow}>+ <span className={styles.tomcatRowLabel}>+ <T>JRE:</T>+ </span>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="JRE"+ value={config.params?.jre ?? ""}+ placeholder={defaultJrePlaceholder}+ onChange={(e) => setParams({ jre: e.target.value })}+ />+ {isTauri() && !isRemoteWindow() && (+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Browse…"+ className={styles.tomcatInlineIconBtn}+ onClick={() =>+ void pickLocalPath(true, config.params?.jre || undefined).then((picked) => {+ if (picked) setParams({ jre: picked });+ })+ }+ />+ )}+ <IconButton+ ref={jreBtnRef}+ icon="chevron-down"+ size="small"+ iconSize={12}+ title="Select JRE"+ className={styles.tomcatInlineChevronBtn}+ onClick={() => setJreMenuOpen((v) => !v)}+ />+ <Menu+ open={jreMenuOpen}+ anchor={jreBtnRef}+ items={jreMenuItems}+ placement="bottom-end"+ onClose={() => setJreMenuOpen(false)}+ />+ </div>+ </div>++ <div className={styles.tomcatSection}>+ <div className={styles.tomcatSectionHeader}>+ <span>+ <T>Tomcat Server Settings</T>+ </span>+ <span className={styles.tomcatSectionLine} />+ </div>+ <div className={styles.tomcatServerSettingsGrid}>+ <div className={styles.tomcatPortsCol}>+ <div className={styles.tomcatPortField}>+ <span className={styles.fieldLabel}>+ <T>HTTP port:</T>+ </span>+ <Input+ mono+ aria-label="HTTP port"+ value={config.params?.httpPort ?? "8080"}+ onChange={(e) => setParams({ httpPort: e.target.value })}+ />+ </div>+ <div className={styles.tomcatPortField}>+ <span className={styles.fieldLabel}>+ <T>HTTPs port:</T>+ </span>+ <Input+ mono+ aria-label="HTTPS port"+ value={config.params?.httpsPort ?? ""}+ onChange={(e) => setParams({ httpsPort: e.target.value })}+ />+ </div>+ <div className={styles.tomcatPortField}>+ <span className={styles.fieldLabel}>+ <T>JMX port:</T>+ </span>+ <Input+ mono+ aria-label="JMX port"+ value={config.params?.jmxPort ?? ""}+ placeholder="Automatic"+ onChange={(e) => setParams({ jmxPort: e.target.value })}+ />+ </div>+ <div className={styles.tomcatPortField}>+ <span className={styles.fieldLabel}>+ <T>AJP port:</T>+ </span>+ <Input+ mono+ aria-label="AJP port"+ value={config.params?.ajpPort ?? ""}+ onChange={(e) => setParams({ ajpPort: e.target.value })}+ />+ </div>+ </div>+ <div className={styles.tomcatFlagsCol}>+ <Checkbox+ checked={config.params?.deployTomcatApps === "true"}+ onChange={(on) => setParams({ deployTomcatApps: on ? "true" : "" })}+ label="Deploy applications configured in Tomcat instance"+ />+ </div>+ </div>+ </div>+ </>+ )}++ {activeTab === "deployment" && (+ <div className={styles.tomcatSection}>+ <div className={styles.tomcatSectionHeader}>+ <span>+ <T>Deploy at the server startup</T>+ </span>+ <span className={styles.tomcatSectionLine} />+ </div>+ <div className={clsx(styles.tomcatBoxPanel, styles.tomcatDeployPanel)}>+ <div className={styles.appServersToolbar} role="toolbar" aria-label={tx("Deploy at the server startup")}>+ <IconButton+ ref={deployAddRef}+ icon="plus"+ size="small"+ iconSize={14}+ title="Add"+ onClick={() => {+ if (artifacts.length > 0 && !isTauri()) {+ select(artifacts[0]!);+ return;+ }+ setDeployMenuOpen((v) => !v);+ }}+ />+ <Menu+ open={deployMenuOpen}+ anchor={deployAddRef}+ items={deployMenuItems}+ placement="bottom-start"+ onClose={() => setDeployMenuOpen(false)}+ />+ <IconButton+ icon="minus"+ size="small"+ iconSize={14}+ title="Remove"+ disabled={noArtifactConfigured}+ onClick={() => setParams({ artifact: "", artifactName: "", deploymentPath: "" })}+ />+ </div>+ {noArtifactConfigured ? (+ <div className={styles.tomcatBoxEmpty}>+ <T>Nothing to deploy</T>+ </div>+ ) : (+ <div className={styles.appServersList}>+ <div className={clsx(styles.editItem, styles.editItemSelected)}>+ <Icon name="file-archive" size={13} className={styles.chooserIcon} />+ <span className={styles.chooserName}>+ {deploymentKind === "artifact"+ ? `${config.params?.artifactName || config.params?.artifact}:war exploded`+ : config.params?.deploymentPath}+ </span>+ <span className={styles.chooserMuted}>{config.params?.contextPath || "/"}</span>+ </div>+ </div>+ )}+ </div>++ {!noArtifactConfigured && (+ <>+ <div className={styles.tomcatFormRow}>+ <span className={styles.tomcatRowLabel}>+ <T>Application context:</T>+ </span>+ <Input+ mono+ aria-label="Context path"+ value={config.params?.contextPath ?? "/"}+ placeholder="/"+ onChange={(e) => setParams({ contextPath: e.target.value })}+ />+ </div>+ <div className={styles.tomcatFormRow}>+ <span className={styles.tomcatRowLabel}>+ <T>Context descriptor:</T>+ </span>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="Context descriptor"+ value={config.params?.contextDescriptor ?? ""}+ placeholder="META-INF/context.xml from application"+ onChange={(e) => setParams({ contextDescriptor: e.target.value })}+ />+ {isTauri() && !isRemoteWindow() && (+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Browse…"+ className={styles.tomcatInlineIconBtn}+ onClick={() =>+ void pickLocalPath(false, config.params?.contextDescriptor || undefined).then((picked) => {+ if (picked) setParams({ contextDescriptor: picked });+ })+ }+ />+ )}+ </div>+ </div>+ </>+ )}+ </div>+ )}++ {activeTab === "logs" && (+ <div className={styles.tomcatSection}>+ <div className={styles.tomcatSaveLogRow}>+ <Checkbox+ checked={config.outputFile !== null && config.outputFile !== undefined}+ onChange={(on) => onChange({ ...config, outputFile: on ? config.outputFile || "" : null })}+ label="Save console output to file:"+ />+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="Console output file"+ disabled={config.outputFile === null || config.outputFile === undefined}+ value={config.outputFile ?? ""}+ onChange={(e) => onChange({ ...config, outputFile: e.target.value })}+ />+ {isTauri() && !isRemoteWindow() && (+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Browse… (⇧⏎)"+ disabled={config.outputFile === null || config.outputFile === undefined}+ className={styles.tomcatInlineIconBtn}+ onClick={() =>+ void pickLocalPath(false, config.outputFile || undefined).then((picked) => {+ if (picked) onChange({ ...config, outputFile: picked });+ })+ }+ />+ )}+ </div>+ </div>+ <Checkbox+ checked={!!config.showOnStdout}+ onChange={(on) => onChange({ ...config, showOnStdout: on })}+ label="Show console when a message is printed to standard output stream"+ />+ <Checkbox+ checked={!!config.showOnStderr}+ onChange={(on) => onChange({ ...config, showOnStderr: on })}+ label="Show console when a message is printed to standard error stream"/>- {!artifacts.length && (- <span className={styles.chooserMuted}>- <T>No WAR modules found. Choose a WAR file or an exploded directory.</T>+ </div>+ )}++ {activeTab === "startup" && (+ <div className={styles.tomcatSection}>+ <div className={styles.tomcatRunnerList} role="listbox" aria-label={tx("Startup runners")}>+ {(+ [+ ["run", "run", "Run"],+ ["debug", "debug", "Debug"],+ ] as const+ ).map(([id, icon, label]) => {+ const sel = startupRunner === id;+ return (+ <button+ key={id}+ type="button"+ role="option"+ aria-selected={sel}+ className={clsx(styles.editItem, sel && styles.editItemSelected)}+ onClick={() => setStartupRunner(id)}+ >+ <Icon name={icon} size={13} className={styles.chooserIcon} />+ <span className={styles.chooserName}>+ <T>{label}</T>+ </span>+ </button>+ );+ })}+ </div>++ <div className={styles.tomcatFormRow}>+ <span className={styles.tomcatRowLabel}>+ <T>Startup script:</T>+ </span>+ <div className={styles.tomcatScriptRow}>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="Startup script"+ disabled={useDefaultStartup}+ value={useDefaultStartup ? defaultStartupCmd : (config.params?.startupScript ?? "")}+ placeholder="Default (bin/catalina.sh run)"+ onChange={(e) => setParams({ startupScript: e.target.value, useDefaultStartup: "false" })}+ />+ {isTauri() && !isRemoteWindow() && (+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Browse…"+ disabled={useDefaultStartup}+ className={styles.tomcatInlineIconBtn}+ onClick={() =>+ void pickLocalPath(false, home || undefined).then((picked) => {+ if (picked) setParams({ startupScript: picked, useDefaultStartup: "false" });+ })+ }+ />+ )}+ </div>+ <Checkbox+ checked={useDefaultStartup}+ onChange={(on) => setParams({ useDefaultStartup: on ? "true" : "false" })}+ label="Use default"+ />+ </div>+ </div>++ <div className={styles.tomcatFormRow}>+ <span className={styles.tomcatRowLabel}>+ <T>Shutdown script:</T>+ </span>+ <div className={styles.tomcatScriptRow}>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="Shutdown script"+ disabled={useDefaultShutdown}+ value={useDefaultShutdown ? defaultShutdownCmd : (config.params?.shutdownScript ?? "")}+ placeholder="Default (bin/catalina.sh stop)"+ onChange={(e) => setParams({ shutdownScript: e.target.value, useDefaultShutdown: "false" })}+ />+ {isTauri() && !isRemoteWindow() && (+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Browse…"+ disabled={useDefaultShutdown}+ className={styles.tomcatInlineIconBtn}+ onClick={() =>+ void pickLocalPath(false, home || undefined).then((picked) => {+ if (picked) setParams({ shutdownScript: picked, useDefaultShutdown: "false" });+ })+ }+ />+ )}+ </div>+ <Checkbox+ checked={useDefaultShutdown}+ onChange={(on) => setParams({ useDefaultShutdown: on ? "true" : "false" })}+ label="Use default"+ />+ </div>+ </div>++ <div className={styles.tomcatSectionHeader}>+ <span>+ <T>Environment Variables</T></span>+ <span className={styles.tomcatSectionLine} />+ </div>+ <Checkbox+ checked={config.params?.passEnvVars !== "false"}+ onChange={(on) => setParams({ passEnvVars: on ? "true" : "false" })}+ label="Pass environment variables"+ />+ <div className={clsx(styles.tomcatBoxPanel, styles.tomcatEnvPanel)}>+ <div className={styles.appServersToolbar} role="toolbar" aria-label={tx("Startup environment variables")}>+ <IconButton+ icon="plus"+ size="small"+ iconSize={14}+ title="Add"+ onClick={() => {+ const next = [...envRows, { name: `VAR_${envRows.length + 1}`, value: "" }];+ setEnvRows(next);+ setSelectedEnvIdx(next.length - 1);+ }}+ />+ <IconButton+ icon="minus"+ size="small"+ iconSize={14}+ title="Remove"+ disabled={envRows.length === 0}+ onClick={() => {+ const next = envRows.filter((_, i) => i !== selectedEnvIdx);+ setEnvRows(next);+ setSelectedEnvIdx(0);+ }}+ />+ <IconButton+ icon="copy"+ size="small"+ iconSize={13}+ title="Copy"+ disabled={envRows.length === 0}+ onClick={() => {+ const row = envRows[selectedEnvIdx];+ if (row) void navigator.clipboard?.writeText(`${row.name}=${row.value}`);+ }}+ />+ <IconButton+ icon="paste"+ size="small"+ iconSize={13}+ title="Paste"+ onClick={() => {+ void navigator.clipboard?.readText().then((text) => {+ if (!text.trim()) return;+ const idx = text.indexOf("=");+ const name = idx >= 0 ? text.slice(0, idx).trim() : text.trim();+ const value = idx >= 0 ? text.slice(idx + 1).trim() : "";+ setEnvRows([...envRows, { name, value }]);+ });+ }}+ />+ </div>+ <div className={styles.tomcatEnvHeader}>+ <span>+ <T>Name</T>+ </span>+ <span>+ <T>Value</T>+ </span>+ </div>+ {envRows.length === 0 ? (+ <div className={styles.tomcatBoxEmpty}>+ <T>No variables</T>+ </div>+ ) : (+ <div className={styles.appServersList}>+ {envRows.map((row, idx) => (+ <div+ key={idx}+ className={clsx(styles.tomcatEnvRow, idx === selectedEnvIdx && styles.tomcatEnvRowSelected)}+ onClick={() => setSelectedEnvIdx(idx)}+ >+ <Input+ mono+ aria-label="Variable name"+ value={row.name}+ onChange={(e) =>+ setEnvRows(envRows.map((r, i) => (i === idx ? { ...r, name: e.target.value } : r)))+ }+ />+ <Input+ mono+ aria-label="Variable value"+ value={row.value}+ onChange={(e) =>+ setEnvRows(envRows.map((r, i) => (i === idx ? { ...r, value: e.target.value } : r)))+ }+ />+ </div>+ ))}+ </div>+ )}+ </div>++ {startupRunner === "debug" && (+ <div className={styles.tomcatDebugConnectionSection}>+ <div className={styles.tomcatDebugPortRow}>+ <span className={styles.tomcatDebugLabel}>+ <T>Port:</T>+ </span>+ <div className={styles.tomcatDebugPortInput}>+ <Input+ mono+ aria-label="Debug port"+ value={debugPort}+ placeholder="Automatic"+ onChange={(e) => setParams({ debugPort: e.target.value })}+ />+ </div>+ </div>+ </div>)}</div>+ )}++ <div className={styles.tomcatSection}>+ <div className={styles.tomcatSectionHeader}>+ <button type="button" className={styles.tomcatSectionToggle} onClick={() => setBeforeLaunchOpen((v) => !v)}>+ <Icon name={beforeLaunchOpen ? "chevron-down" : "chevron-right"} size={12} />+ <T>Before launch</T>+ </button>+ <span className={styles.tomcatSectionLine} />+ </div>+ {beforeLaunchOpen && (+ <>+ {deploymentKind === "artifact" && (+ <div className={clsx(styles.tomcatBoxPanel, styles.tomcatBoxSmall)}>+ <div className={styles.appServersToolbar} role="toolbar" aria-label={tx("Before launch tasks")}>+ <IconButton+ icon="plus"+ size="small"+ iconSize={14}+ title="Add"+ onClick={() => setParams({ buildArtifact: "true" })}+ />+ <IconButton+ icon="minus"+ size="small"+ iconSize={14}+ title="Remove"+ disabled={config.params?.buildArtifact !== "true"}+ onClick={() => setParams({ buildArtifact: "false" })}+ />+ </div>+ <div className={styles.appServersList}>+ {config.params?.buildArtifact === "true" && (+ <div className={styles.editItem}>+ <Icon name="build-project" size={13} className={styles.chooserIcon} />+ <span className={styles.chooserName}>+ <T>Build</T>+ </span>+ </div>+ )}+ </div>+ </div>+ )}+ <div className={styles.tomcatBeforeLaunchFooter}>+ <Checkbox+ checked={config.openToolWindow ?? openByDefault}+ onChange={(on) => onChange({ ...config, openToolWindow: on })}+ label="Activate tool window"+ />+ <Checkbox+ checked={!!config.focusToolWindow}+ onChange={(on) => onChange({ ...config, focusToolWindow: on })}+ label="Focus tool window"+ />+ </div>+ </>+ )}+ </div>+ </div>++ {noArtifactConfigured && (+ <div className={styles.tomcatWarningBar} role="region" aria-label={tx("Configuration warnings")}>+ <span className={styles.tomcatWarningText}>+ <Icon name="warning" size={14} />+ <T>Warning: No artifacts configured</T>+ </span>+ <Button+ size="small"+ icon="bulb-fix"+ onClick={() => {+ setActiveTab("deployment");+ if (artifacts[0]) select(artifacts[0]);+ else setParams({ deployment: "directory" });+ }}+ >+ <T>Fix</T>+ </Button></div>)}- </>++ {vmDialogOpen && (+ <Dialog+ open+ onClose={() => setVmDialogOpen(false)}+ title="VM Options"+ width={520}+ buttons={[{ label: "OK", role: "default", onClick: () => setVmDialogOpen(false) }]}+ >+ <div className={styles.dialogBody}>+ <textarea+ className={styles.textarea}+ rows={8}+ aria-label={tx("VM options editor")}+ value={config.params?.vmOptions ?? ""}+ placeholder="-Xmx1024m -Dfile.encoding=UTF-8"+ onChange={(e) => setParams({ vmOptions: e.target.value.replace(/\r?\n/g, " ") })}+ />+ </div>+ </Dialog>+ )}++ {appServersOpen && (+ <ApplicationServersDialog+ key={allServers.length > 0 ? "loaded" : "empty"}+ initialServers={allServers}+ selectedHome={home}+ onClose={() => setAppServersOpen(false)}+ onApply={(servers, active) => {+ setSavedServers(servers);+ saveServersToStorage(servers);+ setAppServersOpen(false);+ if (active) {+ const shouldRename =+ active.name &&+ (config.name === "Unnamed" ||+ /^Unnamed \(\d+\)$/.test(config.name) ||+ config.name === config.params?.serverName);+ setParams(+ {+ tomcatHome: active.home,+ serverName: active.name,+ tomcatBase: active.base && active.base !== active.home ? active.base : "",+ tomcatLibraries: active.libraries.length ? active.libraries.join(";") : "",+ },+ shouldRename ? active.name : undefined,+ );+ } else {+ setParams({ tomcatHome: "", serverName: "", tomcatBase: "", tomcatLibraries: "" });+ }+ }}+ />+ )}+ </div>+ );+}++function ApplicationServersDialog({+ initialServers,+ selectedHome,+ onClose,+ onApply,+}: {+ initialServers: TomcatServerProfile[];+ selectedHome: string;+ onClose: () => void;+ onApply: (servers: TomcatServerProfile[], selected: TomcatServerProfile | null) => void;+}) {+ const tx = useTx();+ const [servers, setServers] = useState<TomcatServerProfile[]>(() =>+ initialServers.length+ ? initialServers.map((s) => ({ ...s, libraries: [...s.libraries] }))+ : [{ id: "server:1", name: "Tomcat", home: "", base: "", version: "", libraries: [] }],+ );+ const [selectedId, setSelectedId] = useState<string | null>(() => {+ const match = initialServers.find((s) => s.home === selectedHome) ?? initialServers[0];+ return match ? match.id : "server:1";+ });+ const [selectedLib, setSelectedLib] = useState<string | null>(null);+ const [addDialogOpen, setAddDialogOpen] = useState(false);++ const current = servers.find((s) => s.id === selectedId) ?? null;++ const updateCurrent = (patch: Partial<TomcatServerProfile>) => {+ if (!current) return;+ setServers((prev) => prev.map((s) => (s.id === current.id ? { ...s, ...patch } : s)));+ };++ const inspectHome = (targetId: string, nextHome: string) => {+ if (!nextHome.trim()) return;+ void call(commands.runTomcatHome(nextHome))+ .then((info) => {+ const ver = shortVersion(info.version);+ setServers((prev) =>+ prev.map((s) => {+ if (s.id !== targetId || s.home !== nextHome) return s;+ const autoName = !s.name || s.name === "Tomcat" ? defaultServerName(nextHome, info.version) : s.name;+ const autoBase = !s.base || s.base === s.home ? nextHome : s.base;+ const autoLibs = s.libraries.length ? s.libraries : (info.libraries ?? []);+ return {+ ...s,+ home: nextHome,+ base: autoBase,+ name: autoName,+ version: ver,+ libraries: autoLibs,+ tomee: info.tomee,+ };+ }),+ );+ })+ .catch(() => {});+ };++ const removeServer = () => {+ if (!current) return;+ const next = servers.filter((s) => s.id !== current.id);+ setServers(next);+ setSelectedId(next[0]?.id ?? null);+ };++ const addLibrary = async (directory = false) => {+ if (!current) return;+ const picked = await pickLocalPath(directory, current.home || undefined);+ if (!picked || current.libraries.includes(picked)) return;+ updateCurrent({ libraries: [...current.libraries, picked] });+ setSelectedLib(picked);+ };++ const removeLibrary = () => {+ if (!current || !selectedLib) return;+ const nextLibs = current.libraries.filter((l) => l !== selectedLib);+ updateCurrent({ libraries: nextLibs });+ setSelectedLib(nextLibs[0] ?? null);+ };++ return (+ <Dialog+ open+ onClose={onClose}+ title="Application Servers"+ width={720}+ buttons={[+ { label: "Cancel", role: "cancel" },+ {+ label: "OK",+ role: "default",+ onClick: () =>+ onApply(+ servers.filter((s) => s.home.trim()),+ current,+ ),+ },+ ]}+ >+ <div className={styles.appServersBody}>+ <div className={styles.appServersSidebar}>+ <div className={styles.appServersToolbar} role="toolbar" aria-label={tx("Application servers")}>+ <IconButton+ icon="plus"+ size="small"+ iconSize={14}+ title="Add Application Server"+ onClick={() => setAddDialogOpen(true)}+ />+ <IconButton+ icon="minus"+ size="small"+ iconSize={14}+ title="Remove Application Server"+ disabled={!current}+ onClick={removeServer}+ />+ </div>+ <div className={styles.appServersList} role="listbox" aria-label={tx("Application servers")}>+ {servers.map((s) => {+ const sel = s.id === current?.id;+ return (+ <button+ key={s.id}+ type="button"+ role="option"+ aria-selected={sel}+ className={clsx(styles.editItem, sel && styles.editItemSelected)}+ onClick={() => setSelectedId(s.id)}+ >+ <span className={styles.chooserName}>{s.name || <T>Unnamed</T>}</span>+ </button>+ );+ })}+ </div>+ </div>+ <div className={styles.appServersDetail}>+ {current ? (+ <>+ <div className={styles.appServerFieldRow}>+ <span className={styles.appServerFieldLabel}>+ <T>Name:</T>+ </span>+ <Input+ aria-label="Server name"+ value={current.name}+ onChange={(e) => updateCurrent({ name: e.target.value })}+ />+ </div>+ <div className={styles.appServerFieldRow}>+ <span className={styles.appServerFieldLabel}>+ <T>Tomcat Home:</T>+ </span>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="Tomcat Home"+ value={current.home}+ onChange={(e) => {+ const v = e.target.value;+ updateCurrent({+ home: v,+ base: !current.base || current.base === current.home ? v : current.base,+ });+ inspectHome(current.id, v);+ }}+ />+ {isTauri() && !isRemoteWindow() && (+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Browse…"+ className={styles.tomcatInlineIconBtn}+ onClick={() =>+ void pickLocalPath(true, current.home || undefined).then((picked) => {+ if (!picked) return;+ updateCurrent({+ home: picked,+ base: !current.base || current.base === current.home ? picked : current.base,+ });+ inspectHome(current.id, picked);+ })+ }+ />+ )}+ </div>+ </div>+ <div className={styles.appServerFieldRow}>+ <span className={styles.appServerFieldLabel}>+ <T>Tomcat Version:</T>+ </span>+ <span>+ {current.version || "—"}+ {current.tomee ? ` (${tx("TomEE detected")})` : ""}+ </span>+ </div>+ <div className={styles.appServerFieldRow}>+ <span className={styles.appServerFieldLabel}>+ <T>Tomcat base directory:</T>+ </span>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="Tomcat base directory"+ title={tx(+ "Read-only configuration source; leave empty to copy from Tomcat Home. Each launch uses an IDE-managed runtime directory.",+ )}+ value={current.base}+ onChange={(e) => updateCurrent({ base: e.target.value })}+ />+ {isTauri() && !isRemoteWindow() && (+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Browse…"+ className={styles.tomcatInlineIconBtn}+ onClick={() =>+ void pickLocalPath(true, current.base || current.home || undefined).then((picked) => {+ if (picked) updateCurrent({ base: picked });+ })+ }+ />+ )}+ </div>+ </div>+ <div className={styles.tomcatSection}>+ <div className={styles.tomcatSectionHeader}>+ <span>+ <T>Libraries</T>+ </span>+ <span className={styles.tomcatSectionLine} />+ </div>+ <div className={styles.appServersToolbarPlain} role="toolbar" aria-label={tx("Server libraries")}>+ <IconButton+ icon="plus"+ size="small"+ iconSize={14}+ title="Add Library JAR"+ onClick={() => void addLibrary()}+ />+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Add Classes Directory"+ onClick={() => void addLibrary(true)}+ />+ <IconButton+ icon="minus"+ size="small"+ iconSize={14}+ title="Remove Library JAR"+ disabled={!selectedLib}+ onClick={removeLibrary}+ />+ </div>+ <div className={styles.appServersLibs}>+ <div className={styles.appServersLibTree} role="list" aria-label={tx("Classes")}>+ <div className={styles.appServersLibHeader}>+ <Icon name="chevron-down" size={12} />+ <Icon name="folder-library" size={13} />+ <span>+ <T>Classes</T>+ </span>+ </div>+ {current.libraries.map((jar) => (+ <button+ key={jar}+ type="button"+ role="listitem"+ className={clsx(+ styles.appServersLibRow,+ selectedLib === jar && styles.appServersLibRowSelected,+ )}+ onClick={() => setSelectedLib(jar)}+ >+ <Icon name="library" size={13} className={styles.chooserIcon} />+ <span className={styles.chooserName}>{jar}</span>+ </button>+ ))}+ </div>+ </div>+ </div>+ </>+ ) : (+ <div className={styles.editEmpty}>+ <T>No application server selected</T>+ </div>+ )}+ </div>+ </div>+ {addDialogOpen && (+ <AddTomcatServerDialog+ onClose={() => setAddDialogOpen(false)}+ onAdd={(entry) => {+ setServers((prev) => [...prev, entry]);+ setSelectedId(entry.id);+ setAddDialogOpen(false);+ }}+ />+ )}+ </Dialog>+ );+}++function AddTomcatServerDialog({+ onClose,+ onAdd,+}: {+ onClose: () => void;+ onAdd: (server: TomcatServerProfile) => void;+}) {+ const tx = useTx();+ const [home, setHome] = useState("");+ const [base, setBase] = useState("");+ const [version, setVersion] = useState("");+ const [libraries, setLibraries] = useState<string[]>([]);+ const [tomee, setTomee] = useState(false);+ const [validHome, setValidHome] = useState(false);+ const inspectedHome = useRef("");++ const inspect = (nextHome: string) => {+ const trimmed = nextHome.trim();+ inspectedHome.current = trimmed;+ setValidHome(false);+ if (!trimmed) {+ setVersion("");+ setLibraries([]);+ setTomee(false);+ setValidHome(false);+ return;+ }+ void call(commands.runTomcatHome(trimmed))+ .then((info) => {+ if (inspectedHome.current !== trimmed) return;+ setVersion(shortVersion(info.version));+ setLibraries(info.libraries ?? []);+ setTomee(!!info.tomee);+ setValidHome(true);+ })+ .catch(() => {+ if (inspectedHome.current !== trimmed) return;+ setVersion("");+ setLibraries([]);+ setTomee(false);+ setValidHome(false);+ });+ };++ return (+ <Dialog+ open+ onClose={onClose}+ title="Tomcat Server"+ width={440}+ buttons={[+ { label: "Cancel", role: "cancel" },+ {+ label: "OK",+ disabled: !validHome,+ role: "default",+ onClick: () => {+ const id = `server:${Date.now()}`;+ const homeTrimmed = home.trim();+ const baseTrimmed = base.trim() || homeTrimmed;+ onAdd({+ id,+ name: defaultServerName(homeTrimmed, version),+ home: homeTrimmed,+ base: baseTrimmed,+ version,+ libraries,+ tomee,+ });+ },+ },+ ]}+ >+ <div className={styles.addServerDialogBody}>+ <div className={styles.addServerFieldRow}>+ <span className={styles.appServerFieldLabel}>+ <T>Tomcat Home:</T>+ </span>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ autoFocus+ aria-label="New server Tomcat Home"+ value={home}+ onChange={(e) => {+ const next = e.target.value;+ setHome(next);+ if (!base || base === home) setBase(next);+ inspect(next);+ }}+ />+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Browse… (⇧⏎)"+ className={styles.tomcatInlineIconBtn}+ onClick={() => {+ if (isTauri() && !isRemoteWindow()) {+ void pickLocalPath(true, home || undefined).then((picked) => {+ if (!picked) return;+ setHome(picked);+ if (!base || base === home) setBase(picked);+ inspect(picked);+ });+ }+ }}+ />+ </div>+ </div>+ <div className={styles.addServerFieldRow}>+ <span className={styles.appServerFieldLabel}>+ <T>Tomcat Version:</T>+ </span>+ <span>{version}</span>+ </div>+ {!validHome && (+ <div className={styles.addServerErrorRow} role="alert">+ <Icon name="error" size={14} className={styles.addServerErrorIcon} />+ <span>+ <strong>+ <T>Warning:</T>+ </strong>{" "}+ <T>The selected directory is not a valid Tomcat home</T>+ </span>+ </div>+ )}+ <div className={styles.addServerFieldRow}>+ <span className={styles.appServerFieldLabel}>+ <T>Tomcat base directory:</T>+ </span>+ <div className={styles.tomcatInputInside}>+ <Input+ mono+ aria-label="New server Tomcat base directory"+ title={tx(+ "Read-only configuration source; leave empty to copy from Tomcat Home. Each launch uses an IDE-managed runtime directory.",+ )}+ value={base}+ onChange={(e) => setBase(e.target.value)}+ />+ <IconButton+ icon="folder-open"+ size="small"+ iconSize={13}+ title="Browse… (⇧⏎)"+ className={styles.tomcatInlineIconBtn}+ onClick={() => {+ if (isTauri() && !isRemoteWindow()) {+ void pickLocalPath(true, base || home || undefined).then((picked) => {+ if (picked) setBase(picked);+ });+ }+ }}+ />+ </div>+ </div>+ {!base.trim() && (+ <div className={styles.addServerErrorRow} role="alert">+ <Icon name="error" size={14} className={styles.addServerErrorIcon} />+ <span>+ <T>Tomcat base directory path is not specified</T>+ </span>+ </div>+ )}+ </div>+ </Dialog>);}diff --git a/src/features/run/browsePaths.test.tsx b/src/features/run/browsePaths.test.tsxindex 0885c26f6..bc7fc6608 100644--- a/src/features/run/browsePaths.test.tsx+++ b/src/features/run/browsePaths.test.tsx@@ -59,7 +59,7 @@ describe("path fields", () => {it("pick a file or a directory for a configuration type's path fields", async () => {useProject.setState({ project: { root: "/work/app" } as never });- const tomcat = { ...newConfigOfType(tomcatType, []), params: { deployment: "war" } };+ const tomcat = { ...newConfigOfType(tomcatType, []), kind: "tomcat-fields", params: { deployment: "war" } };const onChange = vi.fn();render(<ConfigForm config={tomcat} all={[]} type={tomcatType} errors={{}} onChange={onChange} modifyRequest={0} />);const home = screen.getByRole("textbox", { name: "Tomcat installation directory" });diff --git a/src/features/run/configs.ts b/src/features/run/configs.tsindex 11a2e212e..4e42f832c 100644--- a/src/features/run/configs.ts+++ b/src/features/run/configs.ts@@ -58,6 +58,8 @@ export function configIcon(config: Pick<RunConfig, "kind" | "isTest">): string {return "file-binary";case "spring-boot":return "spring-boot";+ case "tomcat":+ return "tomcat";case "npm":case "bun":return "file-npm";diff --git a/src/features/run/runConfigTypes.test.tsx b/src/features/run/runConfigTypes.test.tsxindex 08f86896f..c95221a0d 100644--- a/src/features/run/runConfigTypes.test.tsx+++ b/src/features/run/runConfigTypes.test.tsx@@ -119,7 +119,9 @@ describe("configuration types", () => {const type = typeFor(kind)!;const original = newConfigOfType(type, []);const config =- kind === "spring-boot" ? withParams(original, { ...original.params, mainClass: "a.Main" }) : original;+ kind === "spring-boot"+ ? withParams(original, { ...original.params, mainClass: "a.Main" })+ : withParams(original, { ...original.params, deploymentMode: "artifact", artifact: "web" });const changed = vi.fn();render(<ConfigForm config={config} all={[config]} type={type} errors={{}} onChange={changed} modifyRequest={0} />);expect(screen.getByRole("button", { name: "On 'Update' action" }).textContent).toContain("Show chooser");diff --git a/src/features/run/session.test.tsx b/src/features/run/session.test.tsxindex cc8f1d5de..39bd3ecf7 100644--- a/src/features/run/session.test.tsx+++ b/src/features/run/session.test.tsx@@ -10,6 +10,7 @@ import {registerMenuGroup,type ToolWindowService,} from "@/workbench/contributions";+import * as navigate from "./navigate";import { ConsoleModel } from "./console";import { ConsoleView, type ConsoleInput } from "./ConsoleView";import { buildRows, mnemonics } from "./ConfigChooser";@@ -120,6 +121,38 @@ describe("HTTP port", () => {});});+describe("Tomcat browser launch", () => {+ it.each([+ ["true", undefined, "http://localhost:18080/demo/"],+ ["true", "https://example.test/custom", "https://example.test/custom"],+ ["false", undefined, null],+ ] as const)(+ "opens the configured URL once after startup (openBrowser=%s)",+ async (openBrowser, browserUrl, expected) => {+ const open = vi.spyOn(navigate, "openUrl").mockResolvedValue();+ try {+ const app = config("tomcat", {+ kind: "tomcat",+ params: { openBrowser, httpPort: "18080", contextPath: "/demo", ...(browserUrl ? { browserUrl } : {}) },+ });+ const session = (await startRun(app))!;+ const console = runtime(session.id)!.console;+ console.append({ kind: "stdout", text: "Starting service Catalina\n" });+ expect(open).not.toHaveBeenCalled();+ console.append({ kind: "stdout", text: "Server startup in [800] milliseconds\n" });+ console.append({ kind: "stdout", text: "Server startup in [900] milliseconds\n" });+ expect(useRun.getState().sessions[0]!.httpPort).toBe(18080);+ if (expected) {+ expect(open).toHaveBeenCalledOnce();+ expect(open).toHaveBeenCalledWith(expected);+ } else expect(open).not.toHaveBeenCalled();+ } finally {+ open.mockRestore();+ }+ },+ );+});+describe("closing a Run tab", () => {it("asks before terminating a running process and keeps the tab when cancelled", async () => {const app = config("app");diff --git a/src/features/run/tomcat.test.tsx b/src/features/run/tomcat.test.tsxindex a06bf316b..13b27bef7 100644--- a/src/features/run/tomcat.test.tsx+++ b/src/features/run/tomcat.test.tsx@@ -1,16 +1,39 @@import { describe, expect, it, vi, afterEach } from "vitest";-import { render, screen, waitFor, cleanup } from "@testing-library/react";+import { render, screen, waitFor, cleanup, fireEvent, within } from "@testing-library/react";import { newConfigOfType, missingParams } from "./types";import { tomcatType, tomcatBrowserUrl, syncTomcatOutputs } from "./tomcat";import { jdwpLaunch } from "./javaDebug";import { TomcatSettings } from "./TomcatSettings";import { typeRows } from "./AddConfigPopup";import { commands } from "@/platform/ipc";+import { useProject } from "@/platform/project";vi.mock("@/platform/ipc", async (importOriginal) => ({...(await importOriginal<typeof import("@/platform/ipc")>()),commands: {- runTomcatHome: vi.fn(async () => ({ status: "ok", data: { version: "Apache Tomcat/10.1.61" } })),+ runTomcatHome: vi.fn(async () => ({+ status: "ok",+ data: {+ version: "Apache Tomcat/10.1.61",+ libraries: [+ "/opt/homebrew/opt/tomcat/libexec/lib/jsp-api.jar",+ "/opt/homebrew/opt/tomcat/libexec/lib/servlet-api.jar",+ ],+ },+ })),+ runTomcatInstallations: vi.fn(async () => ({+ status: "ok",+ data: [+ {+ path: "/opt/homebrew/opt/tomcat/libexec",+ version: "Apache Tomcat/10.1.61",+ libraries: [+ "/opt/homebrew/opt/tomcat/libexec/lib/jsp-api.jar",+ "/opt/homebrew/opt/tomcat/libexec/lib/servlet-api.jar",+ ],+ },+ ],+ })),runTomcatArtifacts: vi.fn(async () => ({status: "ok",data: [@@ -81,7 +104,166 @@ describe("Tomcat Local", () => {}),),);- expect(await screen.findByText("Apache Tomcat/10.1.61")).toBeTruthy();+ expect(await screen.findByText(/Apache Tomcat\/10\.1\.61/)).toBeTruthy();+ });+ it.each(["war", "directory"])(+ "does not replace a configured %s deployment during artifact discovery",+ async (deployment) => {+ const config = newConfigOfType(tomcatType, []);+ config.params = { ...config.params, deployment, deploymentPath: "/external/app", tomcatHome: "/tomcat" };+ const change = vi.fn();+ render(<TomcatSettings config={config} onChange={change} />);+ await screen.findByText(/Apache Tomcat\/10\.1\.61/);+ expect(change).not.toHaveBeenCalled();+ },+ );+ it("validates server ports and supports custom CATALINA_BASE, context descriptor, and instance options", () => {+ const config = newConfigOfType(tomcatType, []);+ config.params = {+ ...config.params,+ tomcatHome: "/tomcat",+ tomcatBase: "/custom/base",+ contextDescriptor: "/project/conf/context.xml",+ deployTomcatApps: "true",+ preserveSessions: "true",+ httpPort: "8080",+ httpsPort: "8443",+ jmxPort: "1099",+ ajpPort: "8009",+ shutdownPort: "8005",+ };+ expect(missingParams(config, tomcatType)).toEqual({});+ config.params.httpsPort = "70000";+ config.params.jmxPort = "0";+ config.params.ajpPort = "abc";+ config.params.shutdownPort = "99999";+ const errors = missingParams(config, tomcatType);+ expect(errors).toHaveProperty("httpsPort");+ expect(errors).toHaveProperty("jmxPort");+ expect(errors).toHaveProperty("ajpPort");+ expect(errors).toHaveProperty("shutdownPort");+ });+ it("auto-selects a detected local Tomcat installation when tomcatHome is blank", async () => {+ const config = newConfigOfType(tomcatType, []);+ const change = vi.fn();+ render(<TomcatSettings config={config} onChange={change} />);+ await waitFor(() =>+ expect(change).toHaveBeenCalledWith(+ expect.objectContaining({+ params: expect.objectContaining({ tomcatHome: "/opt/homebrew/opt/tomcat/libexec" }),+ }),+ ),+ );+ await waitFor(() =>+ expect(change.mock.calls.at(-1)?.[0].params).toMatchObject({+ tomcatHome: "/opt/homebrew/opt/tomcat/libexec",+ artifact: "maven:pom.xml",+ }),+ );+ expect(await screen.findByLabelText("Application server")).toBeTruthy();+ });+ it("opens Application Servers via Configure..., displays libraries, and switches between supported tabs", async () => {+ const config = newConfigOfType(tomcatType, []);+ const change = vi.fn();+ render(<TomcatSettings config={config} onChange={change} />);+ expect(screen.getByText("Warning: No artifacts configured")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Fix" })).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: "Configure..." }));+ expect(await screen.findByText("Application Servers")).toBeTruthy();+ expect(await screen.findByText(/jsp-api\.jar/)).toBeTruthy();+ expect(await screen.findByText(/servlet-api\.jar/)).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: "Add Application Server" }));+ expect(await screen.findByText("The selected directory is not a valid Tomcat home")).toBeTruthy();+ expect(screen.getByText("Tomcat base directory path is not specified")).toBeTruthy();+ fireEvent.change(screen.getByLabelText("New server Tomcat Home"), {+ target: { value: "/opt/homebrew/opt/tomcat/libexec" },+ });+ const cancelBtns = screen.getAllByRole("button", { name: "Cancel" });+ fireEvent.click(cancelBtns[cancelBtns.length - 1]!);++ const nameInput = screen.getByLabelText("Server name");+ fireEvent.change(nameInput, { target: { value: "Tomcat10" } });+ fireEvent.click(screen.getByRole("button", { name: "OK" }));++ expect(change).toHaveBeenCalledWith(+ expect.objectContaining({+ params: expect.objectContaining({+ serverName: "Tomcat10",+ tomcatHome: "/opt/homebrew/opt/tomcat/libexec",+ }),+ }),+ );++ fireEvent.click(screen.getByRole("tab", { name: "Deployment" }));+ expect(screen.getByText("Deploy at the server startup")).toBeTruthy();+ fireEvent.click(screen.getByRole("tab", { name: "Logs" }));+ expect(screen.getByLabelText("Console output file")).toBeTruthy();+ expect(screen.queryByRole("tab", { name: "Code Coverage" })).toBeNull();+ fireEvent.click(screen.getByRole("tab", { name: "Startup/Connection" }));+ expect(screen.getByRole("option", { name: "Debug" })).toBeTruthy();+ expect(screen.queryByRole("option", { name: "Run VisualGC" })).toBeNull();+ expect(screen.getByLabelText("Startup script")).toBeTruthy();+ expect(screen.getByText("Environment Variables")).toBeTruthy();+ });+ it("clears the selected server when all application server profiles are removed", async () => {+ localStorage.clear();+ const config = newConfigOfType(tomcatType, []);+ config.params = {+ ...config.params,+ tomcatHome: "/opt/homebrew/opt/tomcat/libexec",+ serverName: "Tomcat",+ tomcatBase: "/custom/base",+ tomcatLibraries: "/custom/lib.jar",+ };+ const change = vi.fn();+ render(<TomcatSettings config={config} onChange={change} />);+ await screen.findByText(/Apache Tomcat\/10\.1\.61/);+ fireEvent.click(screen.getByRole("button", { name: "Configure..." }));+ fireEvent.click(screen.getByRole("button", { name: "Remove Application Server" }));+ expect(screen.getByText("No application server selected")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "OK" }));+ const params = change.mock.calls.at(-1)?.[0].params;+ expect(params).not.toHaveProperty("tomcatHome");+ expect(params).not.toHaveProperty("serverName");+ expect(params).not.toHaveProperty("tomcatBase");+ expect(params).not.toHaveProperty("tomcatLibraries");+ expect(JSON.parse(localStorage.getItem("openidea.tomcat.servers.v1")!)).toEqual([]);+ });+ it("keeps Debug environment overrides separate from the backend JDWP agent", () => {+ const config = newConfigOfType(tomcatType, []);+ const change = vi.fn();+ render(<TomcatSettings config={config} onChange={change} />);+ expect(screen.queryByLabelText("Browser")).toBeNull();+ expect(screen.queryByLabelText("with JavaScript debugger")).toBeNull();+ fireEvent.click(screen.getByRole("tab", { name: "Startup/Connection" }));+ fireEvent.click(screen.getByRole("option", { name: "Debug" }));+ expect(screen.queryByDisplayValue(/agentlib:jdwp/)).toBeNull();+ fireEvent.click(+ within(screen.getByRole("toolbar", { name: "Startup environment variables" })).getByRole("button", {+ name: "Add",+ }),+ );+ expect(change).toHaveBeenCalledWith(+ expect.objectContaining({+ params: expect.objectContaining({ startupEnvDebug: "VAR_1=" }),+ }),+ );+ });+ it.each([undefined, false, true])("inherits the tool window setting unless overridden (%s)", (override) => {+ const previous = useProject.getState().settings;+ useProject.setState({ settings: { run: { showOnStart: false } } as never });+ try {+ const config = { ...newConfigOfType(tomcatType, []), openToolWindow: override };+ render(<TomcatSettings config={config} onChange={() => {}} />);+ expect((screen.getByRole("checkbox", { name: "Activate tool window" }) as HTMLInputElement).checked).toBe(+ override ?? false,+ );+ } finally {+ cleanup();+ useProject.setState({ settings: previous });+ }});it("reports an invalid installation in the form", async () => {vi.mocked(commands.runTomcatHome).mockRejectedValueOnce(new Error("missing catalina.jar"));diff --git a/src/features/run/tomcat.ts b/src/features/run/tomcat.tsindex c3b2eefc1..caeca49ef 100644--- a/src/features/run/tomcat.ts+++ b/src/features/run/tomcat.ts@@ -4,24 +4,37 @@ import type { RunConfigTypeContribution } from "@/workbench/contributions";import { updatePolicyDefaults, updatePolicyFields } from "./updatePolicies";import { runUpdateBuild } from "./buildUpdate";+const validatePort = (value: string) =>+ /^\d+$/.test(value) && Number(value) > 0 && Number(value) <= 65535 ? null : "Port must be between 1 and 65535";++const validateOptionalPort = (value: string) => (!value.trim() ? null : validatePort(value.trim()));+export const tomcatType: RunConfigTypeContribution = {id: "tomcat",group: "Tomcat Server",label: "Local",- icon: "server",+ icon: "tomcat",description: "Run a WAR application in a local Tomcat server",debugAdapter: "java-debug",terminal: false,defaults: {deployment: "artifact",httpPort: "8080",+ jmxPort: "1099",buildArtifact: "true",openBrowser: "true",...updatePolicyDefaults,},fields: [- ...updatePolicyFields(true),{ key: "tomcatHome", label: "Tomcat installation directory", required: true, mono: true, browse: "directory" },+ {+ key: "tomcatBase",+ label: "Tomcat base directory",+ mono: true,+ browse: "directory",+ placeholder: "IDE-managed isolated base directory",+ hint: "Read-only configuration source; leave empty to copy from Tomcat Home. Each launch uses an IDE-managed runtime directory.",+ },{key: "deployment",label: "Deployment",@@ -51,21 +64,18 @@ export const tomcatType: RunConfigTypeContribution = {: "Enter / or a context path such as /app",},{- key: "httpPort",- label: "HTTP port",- required: true,- validate: (value) =>- /^\d+$/.test(value) && Number(value) > 0 && Number(value) <= 65535 ? null : "Port must be between 1 and 65535",+ key: "contextDescriptor",+ label: "Context descriptor",+ mono: true,+ browse: "file",+ placeholder: "META-INF/context.xml from application",+ hint: "Custom context.xml descriptor; leave empty to use the application's META-INF/context.xml",},{- key: "jre",- label: "JRE",- mono: true,- browse: "directory",- placeholder: "Project JDK",- hint: "Java installation directory; empty uses the project JDK",+ key: "deployTomcatApps",+ label: "Deploy applications configured in Tomcat instance",+ control: "checkbox",},- { key: "vmOptions", label: "VM options", control: "textarea", rows: 2, mono: true },{ key: "openBrowser", label: "Open browser after launch", control: "checkbox" },{key: "browserUrl",@@ -75,6 +85,48 @@ export const tomcatType: RunConfigTypeContribution = {visible: (p) => p.openBrowser === "true",validate: (value) => (/^https?:\/\//i.test(value) ? null : "Enter an HTTP or HTTPS URL"),},+ ...updatePolicyFields(true),+ {+ key: "jre",+ label: "JRE",+ mono: true,+ browse: "directory",+ placeholder: "Project JDK",+ hint: "Java installation directory; empty uses the project JDK",+ },+ { key: "vmOptions", label: "VM options", control: "textarea", rows: 2, mono: true },+ {+ key: "httpPort",+ label: "HTTP port",+ required: true,+ validate: validatePort,+ },+ {+ key: "httpsPort",+ label: "HTTPS port",+ placeholder: "8443",+ validate: validateOptionalPort,+ },+ {+ key: "jmxPort",+ label: "JMX port",+ placeholder: "1099",+ hint: "JMX remote port; leave empty to allocate a free port automatically",+ validate: validateOptionalPort,+ },+ {+ key: "ajpPort",+ label: "AJP port",+ placeholder: "8009",+ validate: validateOptionalPort,+ },+ {+ key: "shutdownPort",+ label: "Shutdown port",+ placeholder: "8005",+ hint: "Tomcat server shutdown port; leave empty to allocate a free port automatically",+ validate: validateOptionalPort,+ },{key: "buildArtifact",label: "Before launch: build the artifact",@@ -118,6 +170,7 @@ export async function syncTomcatOutputs(config: RunConfig, resourcesOnly: booleaexport function tomcatBrowserUrl(config: RunConfig): string {const p = config.params ?? {};+ const host = "localhost";const name =p.artifactName ||p.deploymentPath@@ -127,5 +180,5 @@ export function tomcatBrowserUrl(config: RunConfig): string {?.replace(/\.war$/i, "") ||"";const context = p.contextPath || (name && name !== "ROOT" ? `/${name}` : "/");- return p.browserUrl || `http://localhost:${p.httpPort || "8080"}${context === "/" ? "/" : `${context}/`}`;+ return p.browserUrl || `http://${host}:${p.httpPort || "8080"}${context === "/" ? "/" : `${context}/`}`;}diff --git a/src/features/templates/files/builtins.ts b/src/features/templates/files/builtins.tsindex c869a8137..2300a6b05 100644--- a/src/features/templates/files/builtins.ts+++ b/src/features/templates/files/builtins.ts@@ -387,4 +387,19 @@ export const BUILTIN_FILE_TEMPLATES: readonly FileTemplate[] = [defaultName: ".gitignore",kinds: [{ id: "gitignore", label: ".gitignore file", body: "$END$\n" }],},+ {+ id: "tomcat-context",+ name: "Tomcat Context Descriptor",+ icon: "file-config",+ extension: "xml",+ nameStyle: "asis",+ defaultName: "context",+ kinds: [+ {+ id: "context",+ label: "Tomcat Context Descriptor (context.xml)",+ body: '<?xml version="1.0" encoding="UTF-8"?>\n<Context antiJARLocking="true" path="$END$">\n</Context>\n',+ },+ ],+ },];diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.jsonindex b6c9058f0..14c3e11f1 100644--- a/src/platform/locales/text/en.json+++ b/src/platform/locales/text/en.json@@ -207,6 +207,97 @@"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.","Use Project JDK": "Use Project JDK","JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.": "JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.",+ "Application server": "Application server",+ "Choose a detected Tomcat installation": "Choose a detected Tomcat installation",+ "Tomcat base directory": "Tomcat base directory",+ "IDE-managed isolated base directory": "IDE-managed isolated base directory",+ "Read-only configuration source; leave empty to copy from Tomcat Home. Each launch uses an IDE-managed runtime directory.": "Read-only configuration source; leave empty to copy from Tomcat Home. Each launch uses an IDE-managed runtime directory.",+ "Context descriptor": "Context descriptor",+ "META-INF/context.xml from application": "META-INF/context.xml from application",+ "Custom context.xml descriptor; leave empty to use the application's META-INF/context.xml": "Custom context.xml descriptor; leave empty to use the application's META-INF/context.xml",+ "Deploy applications configured in Tomcat instance": "Deploy applications configured in Tomcat instance",+ "HTTPS port": "HTTPS port",+ "JMX port": "JMX port",+ "JMX remote port; leave empty to allocate a free port automatically": "JMX remote port; leave empty to allocate a free port automatically",+ "AJP port": "AJP port",+ "Shutdown port": "Shutdown port",+ "Tomcat server shutdown port; leave empty to allocate a free port automatically": "Tomcat server shutdown port; leave empty to allocate a free port automatically",+ "Tomcat configuration tabs": "Tomcat configuration tabs",+ "Startup/Connection": "Startup/Connection",+ "Configure...": "Configure...",+ "Open browser": "Open browser",+ "After launch": "After launch",+ "Startup script": "Startup script",+ "Default (bin/catalina.sh run)": "Default (bin/catalina.sh run)",+ "Shutdown script": "Shutdown script",+ "Default (bin/catalina.sh stop)": "Default (bin/catalina.sh stop)",+ "Debug port": "Debug port",+ "Configuration warnings": "Configuration warnings",+ "Warning: No artifacts configured": "Warning: No artifacts configured",+ "Fix": "Fix",+ "Application Servers": "Application Servers",+ "Application servers": "Application servers",+ "Add Application Server": "Add Application Server",+ "Remove Application Server": "Remove Application Server",+ "Server name": "Server name",+ "Tomcat Home": "Tomcat Home",+ "Server libraries": "Server libraries",+ "Add Library JAR": "Add Library JAR",+ "Remove Library JAR": "Remove Library JAR",+ "No application server selected": "No application server selected",+ "Deploy at the server startup": "Deploy at the server startup",+ "Nothing to deploy": "Nothing to deploy",+ "Console output file": "Console output file",+ "Show console when a message is printed to standard output stream": "Show console when a message is printed to standard output stream",+ "Show console when a message is printed to standard error stream": "Show console when a message is printed to standard error stream",+ "Startup runners": "Startup runners",+ "Use default": "Use default",+ "Pass environment variables": "Pass environment variables",+ "Startup environment variables": "Startup environment variables",+ "Variable name": "Variable name",+ "Variable value": "Variable value",+ "Activate tool window": "Activate tool window",+ "Focus tool window": "Focus tool window",+ "Command line arguments for remote JVM": "Command line arguments for remote JVM",+ "TomEE detected": "TomEE detected",+ "Tomcat Context Descriptor": "Tomcat Context Descriptor",+ "Tomcat Context Descriptor (context.xml)": "Tomcat Context Descriptor (context.xml)",+ "Tomcat Server Settings": "Tomcat Server Settings",+ "Application server:": "Application server:",+ "Browse… (⇧⏎)": "Browse… (⇧⏎)",+ "VM options:": "VM options:",+ "Expand (⇧⏎)": "Expand (⇧⏎)",+ "On 'Update' action:": "On 'Update' action:",+ "On frame deactivation:": "On frame deactivation:",+ "JRE:": "JRE:",+ "Select JRE": "Select JRE",+ "HTTP port:": "HTTP port:",+ "HTTPs port:": "HTTPs port:",+ "JMX port:": "JMX port:",+ "AJP port:": "AJP port:",+ "Up": "Up",+ "Application context:": "Application context:",+ "Context descriptor:": "Context descriptor:",+ "Save console output to file:": "Save console output to file:",+ "Shutdown script:": "Shutdown script:",+ "No variables": "No variables",+ "VM Options": "VM Options",+ "Tomcat Home:": "Tomcat Home:",+ "Tomcat Version:": "Tomcat Version:",+ "Tomcat base directory:": "Tomcat base directory:",+ "Add Classes Directory": "Add Classes Directory",+ "Name:": "Name:",+ "URL:": "URL:",+ "Startup script:": "Startup script:",+ "Port:": "Port:",+ "New server Tomcat Home": "New server Tomcat Home",+ "New server Tomcat base directory": "New server Tomcat base directory",+ "Warning:": "Warning:",+ "The selected directory is not a valid Tomcat home": "The selected directory is not a valid Tomcat home",+ "Tomcat base directory path is not specified": "Tomcat base directory path is not specified",+ "VM options editor": "VM options editor",+ "Tomcat server.xml has no HTTPS connector": "Tomcat server.xml has no HTTPS connector",+ "Tomcat server.xml has no AJP connector": "Tomcat server.xml has no AJP connector","Read-only: the table has no primary key to identify rows.": "Read-only: the table has no primary key to identify rows.","Read-only: the query joins several tables.": "Read-only: the query joins several tables.","Read-only: the result is aggregated (DISTINCT, GROUP BY or an aggregate function).": "Read-only: the result is aggregated (DISTINCT, GROUP BY or an aggregate function).",@@ -220,5 +311,6 @@"Could not reopen the project in a container": "Could not reopen the project in a container","Reopen in Container": "Reopen in Container","Builds or starts the project's dev container (devcontainer.json) with the Dev Containers CLI and opens the project in it.": "Builds or starts the project's dev container (devcontainer.json) with the Dev Containers CLI and opens the project in it.",- "devcontainer up exited with {status}": "devcontainer up exited with {status}"+ "devcontainer up exited with {status}": "devcontainer up exited with {status}",+ "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory": "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory"}diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.jsonindex 990b2a494..df50e3194 100644--- a/src/platform/locales/text/es.json+++ b/src/platform/locales/text/es.json@@ -5120,9 +5120,6 @@"Server URL from the HTTP port and context path": "URL del servidor a partir del puerto HTTP y la ruta de contexto","Enter an HTTP or HTTPS URL": "Ingrese una URL HTTP o HTTPS","Before launch: build the artifact": "Antes de iniciar: compilar el artefacto",- "WAR artifact": "Artefacto WAR",- "Choose a WAR module": "Elija un módulo WAR",- "No WAR modules found. Choose a WAR file or an exploded directory.": "No se encontraron módulos WAR. Elija un archivo WAR o un directorio exploded.","Invalid Tomcat installation: check bin/catalina and lib/catalina.jar": "Instalación de Tomcat no válida: verifique bin/catalina y lib/catalina.jar","Update Application": "Actualizar aplicación","Update resources": "Actualizar recursos",diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.jsonindex 323f185f5..d824b7fb3 100644--- a/src/platform/locales/text/fr.json+++ b/src/platform/locales/text/fr.json@@ -4942,9 +4942,6 @@"Server URL from the HTTP port and context path": "URL du serveur d'après le port HTTP et le chemin de contexte","Enter an HTTP or HTTPS URL": "Saisissez une URL HTTP ou HTTPS","Before launch: build the artifact": "Avant le lancement : compiler l'artefact",- "WAR artifact": "Artefact WAR",- "Choose a WAR module": "Choisissez un module WAR",- "No WAR modules found. Choose a WAR file or an exploded directory.": "Aucun module WAR trouvé. Choisissez un fichier WAR ou un répertoire éclaté.","Invalid Tomcat installation: check bin/catalina and lib/catalina.jar": "Installation de Tomcat non valide : vérifiez bin/catalina et lib/catalina.jar","Update Application": "Mettre à jour l'application","Update resources": "Mettre à jour les ressources",diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.jsonindex baf317bfe..a81e99e4f 100644--- a/src/platform/locales/text/ko.json+++ b/src/platform/locales/text/ko.json@@ -5194,9 +5194,6 @@"Server URL from the HTTP port and context path": "HTTP 포트와 컨텍스트 경로로 구성된 서버 URL","Enter an HTTP or HTTPS URL": "HTTP 또는 HTTPS URL을 입력하세요","Before launch: build the artifact": "실행 전: 아티팩트 빌드",- "WAR artifact": "WAR 아티팩트",- "Choose a WAR module": "WAR 모듈 선택",- "No WAR modules found. Choose a WAR file or an exploded directory.": "WAR 모듈을 찾을 수 없습니다. WAR 파일 또는 exploded 디렉터리를 선택하세요.","Invalid Tomcat installation: check bin/catalina and lib/catalina.jar": "잘못된 Tomcat 설치입니다: bin/catalina와 lib/catalina.jar를 확인하세요","Update Application": "애플리케이션 업데이트","Update resources": "리소스 업데이트",diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.jsonindex baca72a8c..4e9ef4ff7 100644--- a/src/platform/locales/text/pl.json+++ b/src/platform/locales/text/pl.json@@ -5071,9 +5071,6 @@"Server URL from the HTTP port and context path": "Adres URL serwera wyznaczony z portu HTTP i ścieżki kontekstu","Enter an HTTP or HTTPS URL": "Wprowadź adres URL typu HTTP lub HTTPS","Before launch: build the artifact": "Przed uruchomieniem: zbuduj artefakt",- "WAR artifact": "Artefakt WAR",- "Choose a WAR module": "Wybierz moduł WAR",- "No WAR modules found. Choose a WAR file or an exploded directory.": "Nie znaleziono modułów WAR. Wybierz plik WAR lub katalog rozpakowany (exploded).","Invalid Tomcat installation: check bin/catalina and lib/catalina.jar": "Nieprawidłowa instalacja Tomcat: sprawdź pliki bin/catalina i lib/catalina.jar","Update Application": "Zaktualizuj aplikację","Update resources": "Zaktualizuj zasoby",diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.jsonindex 0431c0c77..4689f49e0 100644--- a/src/platform/locales/text/pt.json+++ b/src/platform/locales/text/pt.json@@ -5085,9 +5085,6 @@"Server URL from the HTTP port and context path": "URL do servidor a partir da porta HTTP e do caminho de contexto","Enter an HTTP or HTTPS URL": "Digite uma URL HTTP ou HTTPS","Before launch: build the artifact": "Antes de iniciar: compilar o artefato",- "WAR artifact": "Artefato WAR",- "Choose a WAR module": "Escolha um módulo WAR",- "No WAR modules found. Choose a WAR file or an exploded directory.": "Nenhum módulo WAR encontrado. Escolha um arquivo WAR ou um diretório exploded.","Invalid Tomcat installation: check bin/catalina and lib/catalina.jar": "Instalação inválida do Tomcat: verifique bin/catalina e lib/catalina.jar","Update Application": "Atualizar aplicativo","Update resources": "Atualizar recursos",diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.jsonindex 7d9aeb9ea..44afe6d94 100644--- a/src/platform/locales/text/zh.json+++ b/src/platform/locales/text/zh.json@@ -1341,7 +1341,7 @@"Name for the new constant": "新常量的名称","Name for the new variable": "新变量的名称","Name of the current file": "当前文件的名称",- "Name:": "名称:",+ "Name:": "名称:","Named scope": "命名范围","Names (e.g. .DS_Store, *.pyc) hidden from the project tree, navigation bar, search, indexing and Git changes.": "从项目树、导航栏、搜索、索引和 Git 更改中隐藏的名称(例如 .DS_Store、*.pyc)。","Narrow down on typing": "输入时缩小列表范围",@@ -1613,7 +1613,7 @@"Pop Stash": "弹出储藏","Pop Stash (Apply and Drop)": "弹出储藏(应用并丢弃)","Popup type": "弹出类型",- "Port:": "端口:",+ "Port:": "端口:","Postfix Completion": "后缀补全","Poetry Environment": "Poetry 环境","Postfix templates": "后缀模板",@@ -2534,7 +2534,7 @@"UI font": "UI 字体","UI font size": "UI 字体大小","Uninstalled {name}": "已卸载 {name}",- "URL:": "URL:",+ "URL:": "URL:","The controls show the scheme's actual appearance; changes override it.": "控件显示方案的实际外观;修改即覆盖方案。","Uncommitted changes are stashed before the update and restored afterwards.": "更新前会储藏未提交的更改,并在之后恢复。","Underline": "下划线",@@ -3077,7 +3077,7 @@"UTC (+00:00), e.g. Europe/Berlin or +08:00": "UTC (+00:00),例如 Europe/Berlin 或 +08:00","Run keep-alive query each": "执行保持活动查询,间隔","Auto-disconnect after": "在以下时间后自动断开连接",- "Startup script:": "启动脚本:",+ "Startup script:": "启动脚本:","Runs on every new connection, before any other statement.": "在每个新连接上、任何其他语句之前运行。","Passphrase:": "密码短语:","Passphrase": "密码短语",@@ -3777,7 +3777,7 @@"Port must be a number from 1 to 65535": "端口必须是 1 到 65535 之间的数字","JDK version of the remote JVM": "远程 JVM 的 JDK 版本","JDK 9 or later": "JDK 9 或更高版本",- "Command line arguments for remote JVM": "远程 JVM 的命令行参数",+ "Command line arguments for remote JVM": "远程 JVM 命令行参数","Add to the remote JVM's command line (or JAVA_TOOL_OPTIONS)": "添加到远程 JVM 的命令行(或 JAVA_TOOL_OPTIONS)","Use module classpath": "使用模块类路径","Module directory whose sources the debugger shows": "调试器显示其源代码的模块目录",@@ -4857,11 +4857,6 @@"Read-only data source.": "只读数据源。","Use the query console to change ClickHouse data.": "请使用查询控制台修改 ClickHouse 数据。","Read-only: the table has no primary key to identify rows.": "只读:该表没有可用于标识行的主键。",- "Read-only: the query joins several tables.": "只读:查询联接了多个表。",- "Read-only: the result is aggregated (DISTINCT, GROUP BY or an aggregate function).": "只读:结果已聚合(DISTINCT、GROUP BY 或聚合函数)。",- "Read-only: the result combines several queries (UNION / INTERSECT / EXCEPT).": "只读:结果组合了多个查询(UNION / INTERSECT / EXCEPT)。",- "Read-only: the result is not a plain select from a single table.": "只读:结果不是对单个表的普通 SELECT 查询。",- "Read-only: the result has no primary key of {tableLabel}.": "只读:结果中没有 {tableLabel} 的主键。","The session has finished.": "会话已结束。","Variables are available while suspended.": "变量仅在挂起时可用。","Verified": "已验证",@@ -5375,9 +5370,6 @@"Server URL from the HTTP port and context path": "根据 HTTP 端口和上下文路径生成服务器网址","Enter an HTTP or HTTPS URL": "请输入 HTTP 或 HTTPS 网址","Before launch: build the artifact": "启动前:构建部署构件",- "WAR artifact": "WAR 构件",- "Choose a WAR module": "选择 WAR 模块",- "No WAR modules found. Choose a WAR file or an exploded directory.": "未找到 WAR 模块。请选择 WAR 文件或展开目录。","Invalid Tomcat installation: check bin/catalina and lib/catalina.jar": "无效的 Tomcat 安装:请检查 bin/catalina 和 lib/catalina.jar","Update Application": "更新应用","Update resources": "更新资源",@@ -6549,12 +6541,6 @@"Where updates are downloaded from. If it can't be reached, the other source is tried.": "从哪里下载更新。无法连接时会改用另一个源。","CNB (China mirror)": "CNB(国内镜像)","Remote connection cancelled": "远程连接已取消",- "Starting the dev container…": "正在启动开发容器…",- "Command-line tool": "命令行工具",- "Forwarding ports is not supported in a dev container yet": "开发容器暂不支持端口转发",- "Could not reopen the project in a container": "无法在容器中重新打开项目",- "Reopen in Container": "在容器中重新打开",- "Builds or starts the project's dev container (devcontainer.json) with the Dev Containers CLI and opens the project in it.": "使用 Dev Containers CLI 构建或启动项目的开发容器(devcontainer.json),并在其中打开项目。","Xdebug is not loaded in PHP {version}": "PHP {version} 未加载 Xdebug","{php} runs without Xdebug, so breakpoints are skipped. Install Xdebug 3 for this PHP or choose another PHP interpreter.": "{php} 运行时没有 Xdebug,断点会被跳过。请为此 PHP 安装 Xdebug 3,或选择其他 PHP 解释器。","Open PHP Settings": "打开 PHP 设置",@@ -6594,6 +6580,104 @@"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.": "debugpy 未在 120 秒内就绪。请检查运行控制台和容器的 Python 解释器。","Use Project JDK": "使用项目 SDK","JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.": "用于 Maven 同步、构建、目标和测试的 JDK。运行配置中显式设置的 JAVA_HOME 优先。",+ "Application server": "应用服务器",+ "Choose a detected Tomcat installation": "选择已检测到的 Tomcat 安装目录",+ "Tomcat base directory": "Tomcat 基目录",+ "IDE-managed isolated base directory": "IDE 托管的隔离基目录",+ "Read-only configuration source; leave empty to copy from Tomcat Home. Each launch uses an IDE-managed runtime directory.": "只读配置来源;留空则从 Tomcat 主目录复制。每次启动均使用 IDE 托管的运行目录。",+ "Context descriptor": "上下文描述符",+ "META-INF/context.xml from application": "来自应用的 META-INF/context.xml",+ "Custom context.xml descriptor; leave empty to use the application's META-INF/context.xml": "自定义 context.xml 描述符;留空则使用应用的 META-INF/context.xml",+ "Deploy applications configured in Tomcat instance": "部署在 Tomcat 实例中配置的应用程序",+ "HTTPS port": "HTTPS 端口",+ "JMX port": "JMX 端口",+ "JMX remote port; leave empty to allocate a free port automatically": "JMX 远程端口;留空则自动分配空闲端口",+ "AJP port": "AJP 端口",+ "Shutdown port": "关闭端口",+ "Tomcat server shutdown port; leave empty to allocate a free port automatically": "Tomcat 服务器关闭端口;留空则自动分配空闲端口",+ "Tomcat configuration tabs": "Tomcat 配置标签页",+ "Startup/Connection": "启动/连接",+ "Configure...": "配置...",+ "Open browser": "打开浏览器",+ "After launch": "启动后",+ "Startup script": "启动脚本",+ "Default (bin/catalina.sh run)": "默认 (bin/catalina.sh run)",+ "Shutdown script": "关闭脚本",+ "Default (bin/catalina.sh stop)": "默认 (bin/catalina.sh stop)",+ "Debug port": "调试端口",+ "Configuration warnings": "配置警告",+ "Warning: No artifacts configured": "警告:未配置任何构件",+ "Fix": "修复",+ "Application Servers": "应用服务器",+ "Application servers": "应用服务器",+ "Add Application Server": "添加应用服务器",+ "Remove Application Server": "移除应用服务器",+ "Server name": "服务器名称",+ "Tomcat Home": "Tomcat 主目录",+ "Server libraries": "服务器库",+ "Add Library JAR": "添加库 JAR",+ "Remove Library JAR": "移除库 JAR",+ "No application server selected": "未选择应用服务器",+ "Deploy at the server startup": "在服务器启动时部署",+ "Nothing to deploy": "没有可部署的内容",+ "Console output file": "控制台输出文件",+ "Show console when a message is printed to standard output stream": "当消息输出到标准输出流时显示控制台",+ "Show console when a message is printed to standard error stream": "当消息输出到标准错误流时显示控制台",+ "Startup runners": "启动运行器",+ "Use default": "使用默认值",+ "Pass environment variables": "传递环境变量",+ "Startup environment variables": "启动环境变量",+ "Variable name": "变量名称",+ "Variable value": "变量值",+ "Activate tool window": "激活工具窗口",+ "Focus tool window": "聚焦工具窗口",+ "TomEE detected": "已检测到 TomEE",+ "Tomcat Context Descriptor": "Tomcat 上下文描述符",+ "Tomcat Context Descriptor (context.xml)": "Tomcat 上下文描述符 (context.xml)",+ "Tomcat Server Settings": "Tomcat 服务器设置",+ "Application server:": "应用服务器:",+ "Browse… (⇧⏎)": "浏览… (⇧⏎)",+ "VM options:": "VM 选项:",+ "Expand (⇧⏎)": "展开 (⇧⏎)",+ "On 'Update' action:": "执行“更新”操作时:",+ "On frame deactivation:": "窗口失焦时:",+ "JRE:": "JRE:",+ "Select JRE": "选择 JRE",+ "HTTP port:": "HTTP 端口:",+ "HTTPs port:": "HTTPS 端口:",+ "JMX port:": "JMX 端口:",+ "AJP port:": "AJP 端口:",+ "Up": "上移",+ "Application context:": "应用上下文:",+ "Context descriptor:": "上下文描述符:",+ "Save console output to file:": "将控制台输出保存到文件:",+ "Shutdown script:": "关闭脚本:",+ "No variables": "无变量",+ "VM Options": "VM 选项",+ "Tomcat Home:": "Tomcat 主目录:",+ "Tomcat Version:": "Tomcat 版本:",+ "Tomcat base directory:": "Tomcat 基目录:",+ "Add Classes Directory": "添加类目录",+ "New server Tomcat Home": "新服务器 Tomcat 主目录",+ "New server Tomcat base directory": "新服务器 Tomcat 基目录",+ "Warning:": "警告:",+ "The selected directory is not a valid Tomcat home": "所选目录不是有效的 Tomcat 主目录",+ "Tomcat base directory path is not specified": "未指定 Tomcat 基目录路径",+ "VM options editor": "虚拟机选项编辑器",+ "Tomcat server.xml has no HTTPS connector": "Tomcat 的 server.xml 中没有 HTTPS 连接器",+ "Tomcat server.xml has no AJP connector": "Tomcat 的 server.xml 中没有 AJP 连接器",+ "Read-only: the query joins several tables.": "只读:查询联接了多个表。",+ "Read-only: the result is aggregated (DISTINCT, GROUP BY or an aggregate function).": "只读:结果已聚合(DISTINCT、GROUP BY 或聚合函数)。",+ "Read-only: the result combines several queries (UNION / INTERSECT / EXCEPT).": "只读:结果组合了多个查询(UNION / INTERSECT / EXCEPT)。",+ "Read-only: the result is not a plain select from a single table.": "只读:结果不是对单个表的普通 SELECT 查询。",+ "Read-only: the result has no primary key of {tableLabel}.": "只读:结果中没有 {tableLabel} 的主键。",+ "Starting the dev container…": "正在启动开发容器…",+ "Command-line tool": "命令行工具",+ "Forwarding ports is not supported in a dev container yet": "开发容器暂不支持端口转发",+ "Could not reopen the project in a container": "无法在容器中重新打开项目",+ "Reopen in Container": "在容器中重新打开",+ "Builds or starts the project's dev container (devcontainer.json) with the Dev Containers CLI and opens the project in it.": "使用 Dev Containers CLI 构建或启动项目的开发容器(devcontainer.json),并在其中打开项目。","Read-only: the table schema could not be identified in the result database.": "只读:无法确定结果所在数据库中的表架构。",- "devcontainer up exited with {status}": "devcontainer up 已退出,状态为 {status}"+ "devcontainer up exited with {status}": "devcontainer up 已退出,状态为 {status}",+ "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory": "IDE 托管的 Tomcat 运行目录不得与 Tomcat 主目录或基目录重叠"}diff --git a/src/platform/locales/textCatalog.test.ts b/src/platform/locales/textCatalog.test.tsindex 7a6571115..194f56066 100644--- a/src/platform/locales/textCatalog.test.ts+++ b/src/platform/locales/textCatalog.test.ts@@ -97,6 +97,10 @@ const UNTRANSLATED = new Set<string>(["GitHub","PHPStan","Xdebug",+ "Chrome",+ "Safari",+ "Firefox",+ "JaCoCo",// Docker run target placeholder values"compose.yaml","python:3.12",@@ -193,6 +197,7 @@ const UNTRANSLATED = new Set<string>(["Fixup","Fixup…","IDE",+ "localhost","mod tests","Windows (\\r\\n)",// Terms, keywords and acronyms kept in Englishdiff --git a/src/ui/icons.tsx b/src/ui/icons.tsxindex f857b06df..648e31090 100644--- a/src/ui/icons.tsx+++ b/src/ui/icons.tsx@@ -57,6 +57,9 @@ const ICONS = {"gradle-project": "gradle/gradle","gradle-module": "gradle/gradleSubproject","spring-boot": "openidea/runConfigurations/springBoot",+ tomcat: "openidea/runConfigurations/tomcat",+ server: "openidea/runConfigurations/tomcat",+ visualgc: "openidea/runConfigurations/visualgc",file: "fileTypes/text","file-unknown": "fileTypes/unknown","file-code": "fileTypes/anyType",diff --git a/src/ui/openidea/runConfigurations/tomcat.svg b/src/ui/openidea/runConfigurations/tomcat.svgnew file mode 100644index 000000000..58d9825fc--- /dev/null+++ b/src/ui/openidea/runConfigurations/tomcat.svg@@ -0,0 +1,6 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M2.5 5.2L4.2 2.5L6.2 4.3C7.3 4.0 8.7 4.0 9.8 4.3L11.8 2.5L13.5 5.2C14.1 6.8 14.0 9.1 12.8 10.8C11.5 12.5 9.8 13.3 8.0 13.3C6.2 13.3 4.5 12.5 3.2 10.8C2.0 9.1 1.9 6.8 2.5 5.2Z" fill="#FFF4D6" stroke="#D48817" stroke-linejoin="round"/>+<circle cx="6" cy="7.8" r="1" fill="#D48817"/>+<circle cx="10" cy="7.8" r="1" fill="#D48817"/>+<path d="M6.5 10.2C7.3 10.8 8.7 10.8 9.5 10.2" stroke="#D48817" stroke-linecap="round"/>+</svg>diff --git a/src/ui/openidea/runConfigurations/tomcat_dark.svg b/src/ui/openidea/runConfigurations/tomcat_dark.svgnew file mode 100644index 000000000..4d01cde59--- /dev/null+++ b/src/ui/openidea/runConfigurations/tomcat_dark.svg@@ -0,0 +1,6 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M2.5 5.2L4.2 2.5L6.2 4.3C7.3 4.0 8.7 4.0 9.8 4.3L11.8 2.5L13.5 5.2C14.1 6.8 14.0 9.1 12.8 10.8C11.5 12.5 9.8 13.3 8.0 13.3C6.2 13.3 4.5 12.5 3.2 10.8C2.0 9.1 1.9 6.8 2.5 5.2Z" fill="#3D3019" stroke="#E5A524" stroke-linejoin="round"/>+<circle cx="6" cy="7.8" r="1" fill="#E5A524"/>+<circle cx="10" cy="7.8" r="1" fill="#E5A524"/>+<path d="M6.5 10.2C7.3 10.8 8.7 10.8 9.5 10.2" stroke="#E5A524" stroke-linecap="round"/>+</svg>diff --git a/src/ui/openidea/runConfigurations/visualgc.svg b/src/ui/openidea/runConfigurations/visualgc.svgnew file mode 100644index 000000000..106d1894e--- /dev/null+++ b/src/ui/openidea/runConfigurations/visualgc.svg@@ -0,0 +1,5 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<rect x="2.5" y="4" width="9" height="7" rx="1" fill="#EBECF0" stroke="#6C707E"/>+<path d="M4.5 2.5V4M7 2.5V4M9.5 2.5V4M4.5 11V12.5M7 11V12.5" stroke="#6C707E" stroke-linecap="round"/>+<path d="M10.5 9.5L14.5 12L10.5 14.5V9.5Z" fill="#55A76A"/>+</svg>diff --git a/src/ui/openidea/runConfigurations/visualgc_dark.svg b/src/ui/openidea/runConfigurations/visualgc_dark.svgnew file mode 100644index 000000000..b495f0218--- /dev/null+++ b/src/ui/openidea/runConfigurations/visualgc_dark.svg@@ -0,0 +1,5 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<rect x="2.5" y="4" width="9" height="7" rx="1" fill="#2B2D30" stroke="#CED0D6"/>+<path d="M4.5 2.5V4M7 2.5V4M9.5 2.5V4M4.5 11V12.5M7 11V12.5" stroke="#CED0D6" stroke-linecap="round"/>+<path d="M10.5 9.5L14.5 12L10.5 14.5V9.5Z" fill="#5FB86F"/>+</svg>