From 9f643af0699c94f28f62c5e345e515f024996e18 Mon Sep 17 00:00:00 2001 From: Luis Felipe Date: Thu, 26 Nov 2026 10:00:28 -0500 Subject: [PATCH] feat(web): openidea-server --web serves the IDE to a browser (#5134) `openidea-server --web` serves the built frontend and the IDE backend over one HTTP + WebSocket port, directly or behind a reverse proxy that strips or keeps its path prefix. - The rpc dispatcher gains an async `invoke` with a channel sink, so project-host commands, streaming channels and IDE events run over WebSockets as they do over `--stdio`. - Token auth is on by default (a random token unless `--token` or `--no-auth`), binds 127.0.0.1 by default, and WebSocket upgrades must be same-origin. - The browser serves the desktop shell commands with the trust classes the desktop declares (a test keeps them in step), and the desktop menu spec, now in `ide_host::menu`. Recent-project recording and project rename are shared ide-host ops. - WebSocket output is queued without dropping channel data or events. A reloaded page gets back the project its window still has open; after a server restart the page reloads. One tab per window, with Take Over. - Browser fallbacks for the title bar menu, path chooser, clipboard, dialogs, Settings and external links; a reconnecting banner and an unsaved-changes guard. - `scripts/start-web.sh` and the guide (English and Chinese). Co-authored-by: luisfelipe18 <25039923+luisfelipe18@users.noreply.github.com> --- Cargo.lock | 5 + crates/ide-host/Cargo.toml | 7 +- crates/ide-host/src/bin/server.rs | 184 +- crates/ide-host/src/lib.rs | 2 + crates/ide-host/src/menu.rs | 1209 ++++++++++++ crates/ide-host/src/ops/project.rs | 30 + crates/ide-host/src/rpc.rs | 105 +- crates/ide-host/src/web_server/commands.rs | 502 +++++ crates/ide-host/src/web_server/mod.rs | 1736 ++++++++++++++++++ docs/docs.json | 14 +- docs/en/guide/web-server.mdx | 83 + docs/zh/guide/web-server.mdx | 83 + index.html | 4 +- scripts/start-web.sh | 107 ++ src-tauri/src/commands/app.rs | 11 +- src-tauri/src/commands/mod.rs | 19 + src-tauri/src/menu.rs | 1229 +------------ src-tauri/src/state.rs | 10 +- src/features/app/windows.ts | 8 + src/features/settings/index.ts | 3 +- src/main.tsx | 2 + src/platform/choosePath.ts | 11 +- src/platform/clipboard.ts | 13 +- src/platform/dialog.ts | 25 + src/platform/dragOut.ts | 3 +- src/platform/fileManager.ts | 6 +- src/platform/locales/text/en.json | 8 +- src/platform/locales/text/zh.json | 8 +- src/platform/openUrl.ts | 3 +- src/platform/platformInfo.ts | 17 +- src/platform/systemFonts.ts | 3 +- src/platform/webBridge.test.ts | 284 +++ src/platform/webBridge.ts | 544 ++++++ src/windowBoot.tsx | 20 +- src/workbench/TitleBar.tsx | 10 +- src/workbench/WebConnectionBanner.module.css | 38 + src/workbench/WebConnectionBanner.test.tsx | 47 + src/workbench/WebConnectionBanner.tsx | 31 + src/workbench/activate.ts | 5 + src/workbench/webSessionGuard.test.ts | 92 + src/workbench/webSessionGuard.ts | 19 + vite.config.ts | 13 + 42 files changed, 5252 insertions(+), 1301 deletions(-) create mode 100644 crates/ide-host/src/menu.rs create mode 100644 crates/ide-host/src/web_server/commands.rs create mode 100644 crates/ide-host/src/web_server/mod.rs create mode 100644 docs/en/guide/web-server.mdx create mode 100644 docs/zh/guide/web-server.mdx create mode 100755 scripts/start-web.sh create mode 100644 src/platform/webBridge.test.ts create mode 100644 src/platform/webBridge.ts create mode 100644 src/workbench/WebConnectionBanner.module.css create mode 100644 src/workbench/WebConnectionBanner.test.tsx create mode 100644 src/workbench/WebConnectionBanner.tsx create mode 100644 src/workbench/webSessionGuard.test.ts create mode 100644 src/workbench/webSessionGuard.ts diff --git a/Cargo.lock b/Cargo.lock index 62c260e50a..44fdffc106 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4458,13 +4458,18 @@ version = "0.1.53" dependencies = [ "base64 0.22.1", "blake3", + "bytes", "criterion", "dirs 6.0.0", "dunce", "encoding_rs", + "flate2", "futures", "getrandom 0.3.4", "globset", + "http-body-util", + "hyper", + "hyper-util", "ide-agent", "ide-analysis", "ide-build", diff --git a/crates/ide-host/Cargo.toml b/crates/ide-host/Cargo.toml index fb6700729b..e9c319b1fd 100644 --- a/crates/ide-host/Cargo.toml +++ b/crates/ide-host/Cargo.toml @@ -66,7 +66,12 @@ serde_json = { workspace = true, features = ["raw_value"] } toml.workspace = true specta.workspace = true specta-typescript.workspace = true -tokio = { workspace = true, features = ["io-std"] } +bytes = "1" +flate2.workspace = true +http-body-util = "0.1" +hyper = { version = "1", features = ["http1", "server"] } +hyper-util = { version = "0.1", default-features = false, features = ["tokio"] } +tokio = { workspace = true, features = ["io-std", "net", "signal"] } tracing.workspace = true url = "2" tracing-subscriber.workspace = true diff --git a/crates/ide-host/src/bin/server.rs b/crates/ide-host/src/bin/server.rs index ec6ec8054c..08f012458c 100644 --- a/crates/ide-host/src/bin/server.rs +++ b/crates/ide-host/src/bin/server.rs @@ -1,11 +1,16 @@ -//! `openidea-server`: the IDE backend for remote development, either serving one -//! desktop client over stdin / stdout (`--stdio`) or running as a persistent -//! per-project daemon (`--attach `). +//! `openidea-server`: the headless IDE backend. +//! +//! * `--stdio`: JSON-RPC over stdin/stdout for SSH / remote development clients. +//! * `--attach `: persistent per-project remote development daemon. +//! * `--web`: HTTP + WebSocket server exposing the full OpenIDEA web interface on a configurable port. +//! * `--mcp-stdio`: MCP stdio bridge. +//! * `--connect `: TCP relay over stdin/stdout. use ide_host::catalogue::TrustClass; use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND}; use ide_host::plugins::remote_host::RemotePlugins; use ide_host::rpc::{self, Dispatcher}; +use ide_host::web_server::{self, WebServerConfig}; use ide_host::{Host, HostConfig}; use ide_language::LanguageRegistry; use std::path::PathBuf; @@ -17,6 +22,126 @@ enum Mode { Daemon(PathBuf, ide_host::daemon::BuildId), } +fn print_usage() { + eprintln!( + "\ +usage: + openidea-server --web [options] [] + openidea-server --stdio + openidea-server --attach + openidea-server --mcp-stdio [--project ] + openidea-server --connect + openidea-server --version + +web mode options: + --host Bind address (default: $OPENIDEA_HOST or 127.0.0.1) + --port Listen port (default: $OPENIDEA_PORT or 8080) + --base-path Optional reverse-proxy URL prefix (default: $OPENIDEA_BASE_PATH) + --web-dir Built frontend directory (default: $OPENIDEA_WEB_DIR or auto-detected dist/) + --project Workspace directory to open on startup (default: $OPENIDEA_WORKSPACE_DIR) + --home Persistent config/data directory (default: $OPENIDEA_SERVER_HOME or ~/.openidea) + --token Access token ($OPENIDEA_WEB_TOKEN; default: auto-generated random token) + --no-auth Disable token auth ($OPENIDEA_WEB_NO_AUTH=1; use only behind an authenticating proxy) + --no-trust-project Prompt before trusting --project instead of trusting it automatically" + ); +} + +struct ParsedWebArgs { + config: WebServerConfig, + home_override: Option, +} + +fn env_truthy(name: &str) -> bool { + std::env::var(name).ok().is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes")) +} + +fn parse_web_args(args: &[String]) -> Result { + let mut host = std::env::var("OPENIDEA_HOST").unwrap_or_else(|_| "127.0.0.1".into()); + let mut port: u16 = match std::env::var("OPENIDEA_PORT") { + Ok(raw) if !raw.trim().is_empty() => { + raw.trim().parse::().map_err(|_| format!("invalid OPENIDEA_PORT value: {raw}"))? + } + _ => 8080, + }; + let mut base_path = std::env::var("OPENIDEA_BASE_PATH").ok().filter(|s| !s.trim().is_empty()); + let mut web_dir = web_server::default_web_dir(); + let mut project = std::env::var_os("OPENIDEA_WORKSPACE_DIR") + .or_else(|| std::env::var_os("OPENIDEA_PROJECT")) + .filter(|s| !s.is_empty()) + .map(PathBuf::from); + let mut trust_project = true; + let mut no_auth = env_truthy("OPENIDEA_WEB_NO_AUTH"); + let mut auth_token = std::env::var("OPENIDEA_WEB_TOKEN").ok().filter(|s| !s.trim().is_empty()); + let mut home_override: Option = None; + + let mut i = 0; + while i < args.len() { + let arg = args[i].as_str(); + let next_val = |i: &mut usize, flag: &str| -> Result { + *i += 1; + args.get(*i).cloned().ok_or_else(|| format!("missing value for {flag}")) + }; + if arg == "--web" { + i += 1; + continue; + } else if arg == "--host" { + host = next_val(&mut i, "--host")?; + } else if let Some(v) = arg.strip_prefix("--host=") { + host = v.to_owned(); + } else if arg == "--port" || arg == "-p" { + let v = next_val(&mut i, arg)?; + port = v.parse::().map_err(|_| format!("invalid port: {v}"))?; + } else if let Some(v) = arg.strip_prefix("--port=") { + port = v.parse::().map_err(|_| format!("invalid port: {v}"))?; + } else if arg == "--base-path" { + base_path = Some(next_val(&mut i, "--base-path")?); + } else if let Some(v) = arg.strip_prefix("--base-path=") { + base_path = Some(v.to_owned()); + } else if arg == "--web-dir" { + web_dir = PathBuf::from(next_val(&mut i, "--web-dir")?); + } else if let Some(v) = arg.strip_prefix("--web-dir=") { + web_dir = PathBuf::from(v); + } else if arg == "--project" || arg == "--workspace" { + project = Some(PathBuf::from(next_val(&mut i, arg)?)); + } else if let Some(v) = arg.strip_prefix("--project=").or_else(|| arg.strip_prefix("--workspace=")) { + project = Some(PathBuf::from(v)); + } else if arg == "--home" { + home_override = Some(PathBuf::from(next_val(&mut i, "--home")?)); + } else if let Some(v) = arg.strip_prefix("--home=") { + home_override = Some(PathBuf::from(v)); + } else if arg == "--token" { + auth_token = Some(next_val(&mut i, "--token")?); + no_auth = false; + } else if let Some(v) = arg.strip_prefix("--token=") { + auth_token = Some(v.to_owned()); + no_auth = false; + } else if arg == "--no-auth" { + auth_token = None; + no_auth = true; + } else if arg == "--no-trust-project" { + trust_project = false; + } else if arg.starts_with('-') { + return Err(format!("unknown option: {arg}")); + } else if project.is_none() { + project = Some(PathBuf::from(arg)); + } else { + return Err(format!("unexpected positional argument: {arg}")); + } + i += 1; + } + + if no_auth { + auth_token = None; + } else if auth_token.is_none() || auth_token.as_deref() == Some("auto") { + auth_token = Some(web_server::generate_token()); + } + + Ok(ParsedWebArgs { + config: WebServerConfig { host, port, base_path, web_dir, project, trust_project, auth_token }, + home_override, + }) +} + fn main() { let raw_args: Vec = std::env::args().collect(); if let Some(project) = ide_mcp::stdio_request(&raw_args) { @@ -28,6 +153,10 @@ fn main() { println!("openidea-server {} (protocol {})", env!("CARGO_PKG_VERSION"), rpc::PROTOCOL_VERSION); return; } + if args.iter().any(|a| a == "--help" || a == "-h") { + print_usage(); + return; + } if args.first().is_some_and(|a| a == "--connect") { // One forwarded connection (see `ide_host::relay`): stdout carries its bytes. let code = match ide_host::relay::parse_args(&args[1..]).and_then(|(host, port)| { @@ -42,6 +171,7 @@ fn main() { }; std::process::exit(code); } + let base = server_home(); #[cfg(unix)] if args.first().is_some_and(|a| a == "--attach") { @@ -68,6 +198,30 @@ fn main() { }; std::process::exit(code); } + + if args.iter().any(|a| a == "--web") { + let parsed = match parse_web_args(&args) { + Ok(p) => p, + Err(e) => { + eprintln!("error: {e}"); + print_usage(); + std::process::exit(2); + } + }; + init_tracing(); + let base = parsed.home_override.unwrap_or(base); + init_process_env(&base); + let worker_threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(2).clamp(2, 8); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(worker_threads) + .max_blocking_threads(32) + .enable_all() + .build() + .expect("tokio runtime"); + let code = runtime.block_on(web_server::run(parsed.config, base)); + std::process::exit(code); + } + let mode = match args.as_slice() { #[cfg(unix)] [flag, sock, build] if flag == "--daemon" => { @@ -81,27 +235,33 @@ fn main() { [flag, _] if flag == "--attach" => Mode::Stdio, _ if args.iter().any(|a| a == "--stdio") => Mode::Stdio, _ => { - eprintln!( - "usage: openidea-server --stdio | --attach | --mcp-stdio [--project ] | --connect | --version" - ); + print_usage(); std::process::exit(2); } }; - // stdout carries the protocol: logs go to stderr. + init_tracing(); + init_process_env(&base); + let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime"); + let code = runtime.block_on(run(base, mode)); + std::process::exit(code); +} + +fn init_tracing() { + // stdout carries the protocol in --stdio mode: logs always go to stderr. tracing_subscriber::fmt() .with_writer(std::io::stderr) .with_env_filter(tracing_subscriber::EnvFilter::try_from_env("OPENIDEA_LOG").unwrap_or_else(|_| "info".into())) .init(); - // An SSH exec channel gets a minimal environment: take the login shell's, read - // afresh on every start, plus the IDE-managed tools. Before any other thread starts. +} + +fn init_process_env(base: &std::path::Path) { + // An SSH exec channel or container entrypoint gets a minimal environment: inherit login shell + // env plus IDE-managed tools before any other thread starts. ide_host::shell_env::inherit_login_shell_env("openidea-server"); let data_dir = base.join("data"); ide_tools::extend_process_path(&data_dir); ide_dap::adapter::set_tools_root(ide_tools::tools_dir(&data_dir)); ide_sdk::java::add_jdk_root(&ide_tools::jdk::jdks_dir(&data_dir)); - let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime"); - let code = runtime.block_on(run(base, mode)); - std::process::exit(code); } fn server_home() -> PathBuf { diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 49e971832e..16c591a12a 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -15,6 +15,7 @@ mod formatter; mod java_runtime; mod kotlin_bridge; pub mod mcp; +pub mod menu; pub mod notebook; pub mod ops; mod phpstan; @@ -26,6 +27,7 @@ mod requests; pub mod rpc; pub mod shell_env; pub mod trust; +pub mod web_server; pub use project::{Project, history_retention}; diff --git a/crates/ide-host/src/menu.rs b/crates/ide-host/src/menu.rs new file mode 100644 index 0000000000..dc220ab21f --- /dev/null +++ b/crates/ide-host/src/menu.rs @@ -0,0 +1,1209 @@ +//! The application menu as data: the spec table ([`spec`]) every window's menu is built from, +//! and its model ([`model`]) for a menu bar drawn by the frontend. The desktop app renders the +//! spec with the native menu API; `openidea-server --web` serves the model to the browser. + +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::HashMap; +use std::path::Path; + +/// Prefix of Open Recent item ids; the rest of the id is the project path. +pub const RECENT_PREFIX: &str = "recent:"; +/// Prefix of items the frontend lists ([`MenuConfig::dynamic`]): `dyn:` or `dyn:|`. +pub const DYNAMIC_PREFIX: &str = "dyn:"; +/// Action run for an Open Recent entry (argument: the project path). +pub const OPEN_RECENT_ACTION: &str = "file.openRecentProject"; +pub const MAX_RECENT: usize = 15; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Os { + Mac, + Windows, + Linux, +} + +impl Os { + pub fn current() -> Self { + if cfg!(target_os = "macos") { + Os::Mac + } else if cfg!(target_os = "windows") { + Os::Windows + } else { + Os::Linux + } + } +} + +/// Native (role) items, implemented by the OS. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Native { + Undo, + Redo, + Cut, + Copy, + Paste, + SelectAll, + Services, + Hide, + HideOthers, + ShowAll, + Minimize, + Zoom, + BringAllToFront, +} + +impl Native { + pub fn key(self) -> &'static str { + match self { + Native::Undo => "native.undo", + Native::Redo => "native.redo", + Native::Cut => "native.cut", + Native::Copy => "native.copy", + Native::Paste => "native.paste", + Native::SelectAll => "native.selectAll", + Native::Services => "native.services", + Native::Hide => "native.hide", + Native::HideOthers => "native.hideOthers", + Native::ShowAll => "native.showAll", + Native::Minimize => "native.minimize", + Native::Zoom => "native.zoom", + Native::BringAllToFront => "native.bringAllToFront", + } + } + + pub fn default_label(self) -> &'static str { + match self { + Native::Undo => "Undo", + Native::Redo => "Redo", + Native::Cut => "Cut", + Native::Copy => "Copy", + Native::Paste => "Paste", + Native::SelectAll => "Select All", + Native::Services => "Services", + Native::Hide => "Hide OpenIDEA", + Native::HideOthers => "Hide Others", + Native::ShowAll => "Show All", + Native::Minimize => "Minimize", + Native::Zoom => "Zoom", + Native::BringAllToFront => "Bring All to Front", + } + } + + /// Accelerator the OS attaches implicitly (macOS), in keymap syntax. + pub fn implicit_accelerator(self) -> Option<&'static str> { + match self { + Native::Undo => Some("Meta+Z"), + Native::Redo => Some("Meta+Shift+Z"), + Native::Cut => Some("Meta+X"), + Native::Copy => Some("Meta+C"), + Native::Paste => Some("Meta+V"), + Native::SelectAll => Some("Meta+A"), + Native::Hide => Some("Meta+H"), + Native::HideOthers => Some("Meta+Alt+H"), + Native::Minimize => Some("Meta+M"), + _ => None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Entry { + Submenu { + id: &'static str, + label: &'static str, + children: Vec, + }, + /// An IDE action; `id` is the action id. + Action { + id: &'static str, + label: &'static str, + /// Native accelerator (Tauri syntax) that fires natively ([`fires_natively`]) and wins + /// over the keymap's. Only for keys the webview never handles. + accel: Option<&'static str>, + /// Shortcut text after the label, for the Windows/Linux edit items without a keymap binding. + hint: Option<&'static str>, + /// A toggle (IDEA's ToggleAction) drawn with a check mark; on when its id is in + /// [`MenuConfig::checked`]. + check: bool, + }, + Native(Native), + Separator, + /// Open Recent entries, filled from the recent-projects list. + RecentProjects, + /// Items the frontend lists under this slot name (registered tool windows, + /// saved layouts), from [`MenuConfig::dynamic`]. + Dynamic(&'static str), +} + +pub fn sub(id: &'static str, label: &'static str, children: Vec) -> Entry { + Entry::Submenu { id, label, children } +} +pub fn act(id: &'static str, label: &'static str) -> Entry { + Entry::Action { id, label, accel: None, hint: None, check: false } +} +pub fn accel(id: &'static str, label: &'static str, accel: &'static str) -> Entry { + Entry::Action { id, label, accel: Some(accel), hint: None, check: false } +} +pub fn hinted(id: &'static str, label: &'static str, hint: &'static str) -> Entry { + Entry::Action { id, label, accel: None, hint: Some(hint), check: false } +} +pub fn toggle(id: &'static str, label: &'static str) -> Entry { + Entry::Action { id, label, accel: None, hint: None, check: true } +} +pub const SEP: Entry = Entry::Separator; + +/// [`Entry::Dynamic`] slots the frontend fills. +pub const DYNAMIC_TOOL_WINDOWS: &str = "toolWindows"; +pub const DYNAMIC_LAYOUTS: &str = "toolWindowLayouts"; +/// View › Appearance › Status Bar Widgets: every titled widget with its check mark. +pub const DYNAMIC_STATUS_BAR_WIDGETS: &str = "statusBarWidgets"; +/// Tools › entries of plugins (`[[contributes.menus]] menu = "tools"`). +pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools"; +/// Build › Flutter: the Flutter build actions, filled only in Flutter projects. Shown as a submenu +/// first in Build (the Flutter plugin's anchor) when it has items, nothing otherwise. +pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild"; +/// Id (and `menu.` label key) of the Build › Flutter submenu. +pub const FLUTTER_BUILD_MENU: &str = "build.flutter"; + +/// The menu bar for `os`. Labels are English defaults; the frontend replaces +/// them with `menu.` strings from the active locale catalog. +pub fn spec(os: Os) -> Vec { + let mac = os == Os::Mac; + let show_log = match os { + Os::Mac => "Show Log in Finder", + Os::Windows => "Show Log in Explorer", + Os::Linux => "Show Log in Files", + }; + let mut menus = Vec::new(); + + if mac { + menus.push(sub( + "app", + "OpenIDEA", + vec![ + act("app.about", "About OpenIDEA"), + act("app.checkForUpdates", "Check for Updates…"), + SEP, + act("app.installCli", "Install 'openidea' Command"), + act("app.uninstallCli", "Uninstall 'openidea' Command"), + SEP, + act("file.settings", "Settings…"), + SEP, + Entry::Native(Native::Services), + SEP, + Entry::Native(Native::Hide), + Entry::Native(Native::HideOthers), + Entry::Native(Native::ShowAll), + SEP, + accel("app.quit", "Quit OpenIDEA", "CmdOrCtrl+Q"), + ], + )); + } + + let mut file = vec![ + sub( + "new", + "New", + vec![ + act("file.newProject", "Project…"), + act("workspace.create", "Workspace…"), + act("vcs.cloneProject", "Project from Version Control…"), + SEP, + act("file.new", "File…"), + act("file.newScratchFile", "Scratch File"), + act("file.newUntitled", "Untitled File"), + ], + ), + act("file.openProject", "Open…"), + act("file.openFile", "Open File…"), + act("file.openInNewWindow", "Open in New Window…"), + sub( + "openRecent", + "Open Recent", + vec![Entry::RecentProjects, SEP, act("welcome.recentProjects", "Manage Projects…")], + ), + act("project.attach", "Attach Project…"), + SEP, + act("workspace.open", "Open Workspace…"), + act("workspace.manage", "Manage Workspace…"), + SEP, + act("file.closeProject", "Close Project"), + act("file.renameProject", "Rename Project…"), + SEP, + act("remote.connect", "Remote Development…"), + act("remote.reopenInContainer", "Reopen in Container"), + act("remote.disconnect", "Disconnect from Remote Host"), + act("remote.stopBackend", "Stop Remote Backend"), + act("remote.reloadEnvironment", "Reload Environment"), + SEP, + act("file.save", "Save All"), + act("file.reloadAllFromDisk", "Reload All from Disk"), + sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]), + SEP, + act("file.projectStructure", "Project Structure…"), + SEP, + act("file.invalidateCaches", "Invalidate Caches…"), + SEP, + sub( + "manageIdeSettings", + "Manage IDE Settings", + vec![ + act("file.exportSettings", "Export Settings…"), + act("file.importSettings", "Import Settings…"), + act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"), + ], + ), + sub( + "newProjectsSetup", + "New Projects Setup", + vec![act("file.newProjectsSettings", "Settings for New Projects…")], + ), + SEP, + act("file.togglePowerSave", "Power Save Mode"), + ]; + if !mac { + // macOS keeps Settings… and Quit in the application menu. + file.extend([SEP, act("file.settings", "Settings…"), SEP, accel("app.quit", "Exit", "Ctrl+Q")]); + } + menus.push(sub("file", "File", file)); + + let find = sub( + "find", + "Find", + vec![ + act("find.inFile", "Find…"), + act("find.replaceInFile", "Replace…"), + SEP, + act("find.inPath", "Find in Files…"), + act("find.replaceInPath", "Replace in Files…"), + act("find.structural", "Search Structurally…"), + act("find.replaceStructural", "Replace Structurally…"), + SEP, + act("find.usages", "Find Usages"), + act("find.showUsages", "Show Usages"), + ], + ); + let macros = || { + sub( + "macros", + "Macros", + vec![ + act("macro.startRecording", "Start Macro Recording"), + act("macro.stopRecording", "Stop Macro Recording"), + act("macro.playBack", "Play Back Last Macro"), + SEP, + act("macro.playSaved", "Play Saved Macros…"), + act("macro.edit", "Edit Macros…"), + ], + ) + }; + let bookmarks = || { + sub( + "bookmarks", + "Bookmarks", + vec![ + act("navigate.toggleBookmark", "Toggle Bookmark"), + act("navigate.toggleBookmarkWithMnemonic", "Toggle Bookmark with Mnemonic"), + SEP, + act("navigate.showBookmarks", "Show All Bookmarks…"), + act("navigate.nextBookmark", "Next Bookmark"), + act("navigate.prevBookmark", "Previous Bookmark"), + ], + ) + }; + let edit = if mac { + vec![ + Entry::Native(Native::Undo), + Entry::Native(Native::Redo), + SEP, + Entry::Native(Native::Cut), + Entry::Native(Native::Copy), + Entry::Native(Native::Paste), + act("code.pasteFromHistory", "Paste from History…"), + act("code.pasteAsPlainText", "Paste as Plain Text"), + Entry::Native(Native::SelectAll), + SEP, + find, + SEP, + act("editor.copyPath", "Copy Path"), + act("editor.copyReference", "Copy Reference"), + SEP, + act("code.sortLines", "Sort Lines"), + act("code.reverseLines", "Reverse Lines"), + SEP, + act("editor.toggleColumnSelection", "Column Selection Mode"), + SEP, + macros(), + bookmarks(), + ] + } else { + // GTK/Win32 accelerators would swallow these keys before the webview, so + // they are plain items routed to `document.execCommand` by the frontend. + vec![ + hinted("edit.undo", "Undo", "Ctrl+Z"), + hinted("edit.redo", "Redo", "Ctrl+Shift+Z"), + SEP, + hinted("edit.cut", "Cut", "Ctrl+X"), + hinted("edit.copy", "Copy", "Ctrl+C"), + hinted("edit.paste", "Paste", "Ctrl+V"), + act("code.pasteFromHistory", "Paste from History…"), + act("code.pasteAsPlainText", "Paste as Plain Text"), + hinted("edit.selectAll", "Select All", "Ctrl+A"), + SEP, + find, + SEP, + act("editor.copyPath", "Copy Path"), + act("editor.copyReference", "Copy Reference"), + SEP, + act("code.sortLines", "Sort Lines"), + act("code.reverseLines", "Reverse Lines"), + SEP, + act("editor.toggleColumnSelection", "Column Selection Mode"), + SEP, + macros(), + bookmarks(), + ] + }; + menus.push(sub("edit", "Edit", edit)); + + menus.push(sub( + "view", + "View", + vec![ + sub( + "toolWindows", + "Tool Windows", + vec![Entry::Dynamic(DYNAMIC_TOOL_WINDOWS), SEP, act("toolwindow.hideAll", "Hide All Tool Windows")], + ), + sub( + "appearance", + "Appearance", + vec![ + act("editor.toggleZen", "Enter Distraction Free Mode"), + act("window.toggleFullScreen", "Toggle Full Screen"), + toggle("view.toggleCompactMode", "Compact Mode"), + toggle("view.togglePresentationAssistant", "Presentation Assistant"), + SEP, + act("view.zoomIn", "Zoom In IDE"), + act("view.zoomOut", "Zoom Out IDE"), + act("view.resetZoom", "Reset IDE Zoom"), + SEP, + act("view.toggleTheme", "Toggle Light/Dark Theme"), + act("toolbar.customize", "Customize Main Toolbar…"), + SEP, + toggle("view.toggleToolbar", "Toolbar"), + toggle("view.toggleToolWindowBars", "Tool Window Bars"), + sub( + "navigationBar", + "Navigation Bar", + vec![ + toggle("view.navigationBarTop", "Top"), + toggle("view.navigationBarStatusBar", "Status Bar"), + toggle("view.navigationBarHidden", "Don't Show"), + ], + ), + toggle("view.toggleStatusBar", "Status Bar"), + sub("statusBarWidgets", "Status Bar Widgets", vec![Entry::Dynamic(DYNAMIC_STATUS_BAR_WIDGETS)]), + ], + ), + sub( + "activeEditor", + "Active Editor", + vec![ + act("editor.toggleSoftWrap", "Soft-Wrap"), + act("editor.toggleRenderedDocs", "Render Documentation Comments"), + ], + ), + SEP, + act("code.quickDefinition", "Quick Definition"), + act("code.quickTypeDefinition", "Quick Type Definition"), + SEP, + act("navigate.recentLocations", "Recent Locations"), + act("navigate.recentFiles", "Recent Files"), + act("localHistory.recentChanges", "Recent Changes"), + SEP, + act("diff.compareWithClipboard", "Compare with Clipboard"), + SEP, + act("view.quickSwitchScheme", "Quick Switch Scheme…"), + SEP, + act("editor.resetFontSize", "Reset Font Size"), + act("editor.resetFontSizeAll", "Reset Font Size in All Editors"), + SEP, + act("view.notifications", "Notifications"), + ], + )); + + menus.push(sub( + "navigate", + "Navigate", + vec![ + act("navigate.searchEverywhere", "Search Everywhere"), + act("navigate.gotoClass", "Class…"), + act("navigate.gotoFile", "File…"), + act("navigate.gotoSymbol", "Symbol…"), + act("navigate.gotoLine", "Line/Column…"), + SEP, + act("navigate.back", "Back"), + act("navigate.forward", "Forward"), + act("navigate.lastEditLocation", "Last Edit Location"), + act("navigate.nextEditLocation", "Next Edit Location"), + SEP, + act("navigate.declaration", "Declaration or Usages"), + act("navigate.implementation", "Implementation(s)"), + act("navigate.typeDeclaration", "Type Declaration"), + act("navigate.superMethod", "Super Method"), + act("navigate.gotoTest", "Test"), + act("navigate.relatedSymbol", "Related Symbol…"), + SEP, + act("navigate.fileStructure", "File Structure"), + act("navigate.showFilePath", "File Path"), + act("navigate.callHierarchy", "Call Hierarchy"), + act("navigate.typeHierarchy", "Type Hierarchy"), + act("navigate.customRegion", "Custom Folding…"), + SEP, + act("navigate.nextMethod", "Next Method"), + act("navigate.previousMethod", "Previous Method"), + SEP, + act("navigate.nextError", "Next Highlighted Error"), + act("navigate.prevError", "Previous Highlighted Error"), + SEP, + act("navigate.selectIn", "Select In…"), + ], + )); + + menus.push(sub( + "code", + "Code", + vec![ + sub( + "completion", + "Code Completion", + vec![ + act("code.completion", "Basic"), + act("code.smartTypeCompletion", "Smart Type"), + SEP, + act("code.cyclicExpandWord", "Cyclic Expand Word"), + act("code.cyclicExpandWordBackward", "Cyclic Expand Word (Backward)"), + ], + ), + act("code.parameterInfo", "Parameter Info"), + act("code.quickDocumentation", "Quick Documentation"), + act("code.expressionTypeInfo", "Expression Type Info"), + act("code.showErrorDescription", "Error Description"), + act("editor.contextInfo", "Context Info"), + act("code.showIntentions", "Show Context Actions"), + act("code.generate", "Generate…"), + act("code.overrideMethods", "Override Methods…"), + act("code.implementMethods", "Implement Methods…"), + SEP, + act("code.insertLiveTemplate", "Insert Live Template…"), + act("code.surroundWith", "Surround With…"), + act("code.surroundWithLiveTemplate", "Surround with Live Template…"), + act("code.unwrap", "Unwrap/Remove…"), + SEP, + act("code.reformat", "Reformat Code"), + act("code.autoIndentLines", "Auto-Indent Lines"), + act("code.optimizeImports", "Optimize Imports"), + act("code.rearrange", "Rearrange Code"), + act("code.cleanup", "Code Cleanup…"), + SEP, + act("code.commentLine", "Comment with Line Comment"), + act("code.commentBlock", "Comment with Block Comment"), + SEP, + act("code.extendSelection", "Extend Selection"), + act("code.shrinkSelection", "Shrink Selection"), + act("code.duplicateLine", "Duplicate Line or Selection"), + act("code.deleteLine", "Delete Line"), + act("code.moveStatementUp", "Move Statement Up"), + act("code.moveStatementDown", "Move Statement Down"), + act("code.moveElementLeft", "Move Element Left"), + act("code.moveElementRight", "Move Element Right"), + act("code.moveLineUp", "Move Line Up"), + act("code.moveLineDown", "Move Line Down"), + SEP, + sub( + "folding", + "Folding", + vec![ + act("code.foldToggle", "Expand/Collapse"), + act("code.foldAll", "Collapse All"), + act("code.unfoldAll", "Expand All"), + sub( + "expandToLevel", + "Expand to Level", + vec![ + act("code.expandToLevel1", "1"), + act("code.expandToLevel2", "2"), + act("code.expandToLevel3", "3"), + act("code.expandToLevel4", "4"), + act("code.expandToLevel5", "5"), + ], + ), + sub( + "expandAllToLevel", + "Expand All to Level", + vec![ + act("code.expandAllToLevel1", "1"), + act("code.expandAllToLevel2", "2"), + act("code.expandAllToLevel3", "3"), + act("code.expandAllToLevel4", "4"), + act("code.expandAllToLevel5", "5"), + ], + ), + SEP, + act("code.expandDocComments", "Expand Doc Comments"), + act("code.collapseDocComments", "Collapse Doc Comments"), + SEP, + act("code.collapseBlock", "Fold Code Block"), + act("code.foldSelection", "Fold Selection / Remove Region"), + ], + ), + SEP, + act("analyze.inspectCode", "Inspect Code…"), + sub( + "analyzeCode", + "Analyze Code", + vec![ + act("analyze.inspectFile", "Inspect Current File"), + act("analyze.locateDuplicates", "Locate Duplicates…"), + ], + ), + act("analyze.stackTrace", "Analyze Stack Trace or Thread Dump…"), + ], + )); + + menus.push(sub( + "refactor", + "Refactor", + vec![ + act("refactor.thisMenu", "Refactor This…"), + SEP, + act("refactor.rename", "Rename…"), + act("refactor.changeSignature", "Change Signature…"), + SEP, + act("refactor.extractVariable", "Introduce Variable…"), + act("refactor.extractConstant", "Introduce Constant…"), + act("refactor.extractField", "Introduce Field…"), + act("refactor.extractParameter", "Introduce Parameter…"), + act("refactor.extractMethod", "Extract Method…"), + act("refactor.extractInterface", "Extract Interface…"), + act("refactor.inline", "Inline…"), + SEP, + act("refactor.pullMembersUp", "Pull Members Up…"), + act("refactor.pushMembersDown", "Push Members Down…"), + SEP, + act("refactor.move", "Move…"), + act("project.copyElement", "Copy…"), + act("refactor.safeDelete", "Safe Delete…"), + ], + )); + + menus.push(sub( + "build", + "Build", + vec![ + Entry::Dynamic(DYNAMIC_FLUTTER_BUILD), + act("build.buildProject", "Build Project"), + act("build.buildModule", "Build Module"), + act("build.compileFile", "Recompile"), + act("build.rebuildProject", "Rebuild Project"), + SEP, + act("build.buildArtifacts", "Build Artifacts"), + ], + )); + + menus.push(sub( + "run", + "Run", + vec![ + act("run.run", "Run"), + act("run.debug", "Debug"), + act("run.runContext", "Run Context Configuration"), + act("run.debugContext", "Debug Context Configuration"), + act("run.coverage", "Run with Coverage"), + act("run.profile", "Profile"), + act("run.stop", "Stop"), + SEP, + act("run.chooseConfig", "Run…"), + act("run.chooseDebugConfig", "Debug…"), + act("runAnything.show", "Run Anything…"), + act("run.editConfigs", "Edit Configurations…"), + act("run.updateApplication", "Update Application"), + act("debug.attachToProcess", "Attach to Process…"), + SEP, + act("debug.resume", "Resume Program"), + act("debug.pause", "Pause Program"), + act("debug.stepOver", "Step Over"), + act("debug.forceStepOver", "Force Step Over"), + act("debug.stepInto", "Step Into"), + act("debug.forceStepInto", "Force Step Into"), + act("debug.smartStepInto", "Smart Step Into"), + act("debug.stepOut", "Step Out"), + act("debug.runToCursor", "Run to Cursor"), + act("debug.forceRunToCursor", "Force Run to Cursor"), + act("debug.showExecutionPoint", "Show Execution Point"), + act("debug.resetFrame", "Reset Frame"), + act("debug.evaluate", "Evaluate Expression…"), + act("debug.quickEvaluate", "Quick Evaluate Expression"), + sub( + "debuggingActions", + "Debugging Actions", + vec![act("debug.reloadChangedClasses", "Reload Changed Classes")], + ), + SEP, + act("coverage.hide", "Hide Coverage"), + SEP, + act("debug.toggleBreakpoint", "Toggle Line Breakpoint"), + act("debug.toggleTemporaryBreakpoint", "Toggle Temporary Line Breakpoint"), + act("debug.toggleMethodBreakpoint", "Toggle Method Breakpoint"), + act("debug.toggleFieldWatchpoint", "Toggle Field Watchpoint"), + act("debug.viewBreakpoints", "View Breakpoints…"), + ], + )); + + menus.push(sub( + "git", + "Git", + vec![ + act("vcs.commit", "Commit…"), + act("vcs.push", "Push…"), + act("vcs.update", "Update Project…"), + act("vcs.pull", "Pull…"), + act("vcs.fetch", "Fetch"), + act("vcs.unshallow", "Fetch Full History"), + SEP, + // Operation items (Abort Merge, Continue Rebase…) are enabled only while it is in progress. + act("vcs.merge", "Merge…"), + act("vcs.merge.abort", "Abort Merge"), + act("vcs.rebase", "Rebase…"), + act("vcs.rebase.abort", "Abort Rebase"), + act("vcs.rebase.continue", "Continue Rebase"), + act("vcs.rebase.skip", "Skip Commit"), + act("vcs.resolveConflicts", "Resolve Conflicts…"), + SEP, + act("vcs.branches", "Branches…"), + act("vcs.newBranch", "New Branch…"), + act("vcs.newTag", "New Tag…"), + act("vcs.resetHead", "Reset HEAD…"), + SEP, + act("vcs.newWorktree", "New Worktree…"), + act("vcs.worktrees", "Worktrees…"), + SEP, + act("vcs.showLog", "Show Git Log"), + sub( + "gitPatch", + "Patch", + vec![ + act("vcs.createPatch", "Create Patch…"), + act("vcs.applyPatch", "Apply Patch…"), + act("vcs.applyPatchFromClipboard", "Apply Patch from Clipboard…"), + ], + ), + sub( + "gitUncommittedChanges", + "Uncommitted Changes", + vec![ + act("vcs.shelve", "Shelve Changes…"), + act("vcs.showShelf", "Show Shelf"), + act("vcs.stash", "Stash Changes…"), + act("vcs.showStashes", "Show Stash"), + act("vcs.unstash", "Unstash Changes…"), + act("vcs.rollback", "Rollback…"), + ], + ), + sub( + "gitCurrentFile", + "Current File", + vec![ + act("vcs.addToVcs", "Add to VCS"), + SEP, + act("vcs.annotate", "Annotate with Git Blame"), + act("vcs.showDiff", "Show Diff"), + act("vcs.compareWithBranch", "Compare with Branch or Revision…"), + act("vcs.showHistory", "Show History"), + act("vcs.showHistoryForSelection", "Show History for Selection"), + SEP, + act("vcs.localHistory", "Local History"), + act("localHistory.putLabel", "Put Label…"), + ], + ), + SEP, + sub( + "gitHub", + "GitHub", + vec![ + act("github.pullRequests", "View Pull Requests"), + act("github.createPullRequest", "Create Pull Request…"), + act("github.checkoutPullRequest", "Checkout Pull Request…"), + act("github.openInBrowser", "Open on GitHub"), + ], + ), + act("vcs.manageRemotes", "Manage Remotes…"), + act("vcs.clone", "Clone…"), + SEP, + act("vcs.operations", "VCS Operations Popup…"), + SEP, + act("vcs.revert.continue", "Continue Revert"), + act("vcs.revert.abort", "Abort Revert"), + act("vcs.cherryPick.continue", "Continue Cherry-Pick"), + act("vcs.cherryPick.abort", "Abort Cherry-Pick"), + ], + )); + + let mut tools = vec![ + act("http.newRequest", "New HTTP Request"), + act("http.showToolWindow", "HTTP Client"), + SEP, + act("db.showToolWindow", "Database"), + act("db.newDataSource", "New Data Source…"), + act("db.openConsole", "Open Query Console"), + SEP, + act("ssh.startSession", "Start SSH Session…"), + act("ssh.configurations", "SSH Configurations…"), + sub( + "deployment", + "Deployment", + vec![ + act("deployment.uploadToDefault", "Upload to Default Server"), + act("deployment.uploadTo", "Upload to…"), + act("deployment.downloadFromDefault", "Download from Default Server"), + act("deployment.downloadFrom", "Download from…"), + act("deployment.syncWith", "Sync with Deployed…"), + act("deployment.deleteFromServer", "Delete from Server"), + SEP, + act("deployment.toggleAutoUpload", "Automatic Upload"), + act("deployment.browseRemoteHost", "Browse Remote Host"), + act("deployment.openInBrowser", "Open in Browser"), + act("deployment.configure", "Configuration…"), + ], + ), + SEP, + act("vim.toggle", "Vim"), + Entry::Dynamic(DYNAMIC_PLUGIN_TOOLS), + ]; + if !mac { + tools.extend([ + SEP, + act("app.installCli", "Install 'openidea' Command"), + act("app.uninstallCli", "Uninstall 'openidea' Command"), + ]); + } + menus.push(sub("tools", "Tools", tools)); + + let mut window = Vec::new(); + if mac { + window.extend([Entry::Native(Native::Minimize), Entry::Native(Native::Zoom), SEP]); + } + window.extend([ + sub( + "toolWindowLayouts", + "Tool Window Layouts", + vec![ + toggle("layout.restoreDefault", "Restore Default Layout"), + Entry::Dynamic(DYNAMIC_LAYOUTS), + SEP, + act("layout.restoreCurrent", "Restore Current Layout"), + act("layout.saveCurrent", "Save Changes in Current Layout"), + act("layout.save", "Save Current Layout as…"), + ], + ), + SEP, + sub( + "activeToolWindow", + "Active Tool Window", + vec![ + act("toolwindow.hideActive", "Hide Active Tool Window"), + act("toolwindow.hideSide", "Hide Side Tool Windows"), + act("toolwindow.maximize", "Maximize Tool Window"), + act("toolwindow.closeContent", "Close Active Tab"), + sub( + "resizeToolWindow", + "Resize", + vec![ + act("toolwindow.resizeLeft", "Stretch to Left"), + act("toolwindow.resizeRight", "Stretch to Right"), + act("toolwindow.resizeUp", "Stretch to Top"), + act("toolwindow.resizeDown", "Stretch to Bottom"), + ], + ), + SEP, + act("toolwindow.jumpToLast", "Jump to Last Tool Window"), + act("toolwindow.focusEditor", "Focus Editor"), + ], + ), + sub( + "editorTabs", + "Editor Tabs", + vec![ + act("editor.nextTab", "Select Next Tab"), + act("editor.prevTab", "Select Previous Tab"), + SEP, + act("editor.pinTab", "Pin Tab"), + act("editor.closeTab", "Close Tab"), + act("editor.closeOtherTabs", "Close Other Tabs"), + act("editor.closeAllTabs", "Close All Tabs"), + act("editor.reopenClosedTab", "Reopen Closed Tab"), + SEP, + act("editor.splitRight", "Split Right"), + act("editor.splitDown", "Split Down"), + act("editor.unsplit", "Unsplit"), + act("editor.moveToOppositeGroup", "Move to Opposite Group"), + act("editor.openInOppositeGroup", "Open in Opposite Group"), + act("editor.changeSplitOrientation", "Change Splitter Orientation"), + act("editor.unsplitAll", "Unsplit All"), + act("editor.nextSplitter", "Go to Next Splitter"), + act("editor.prevSplitter", "Go to Previous Splitter"), + ], + ), + SEP, + act("window.new", "New Window"), + act("window.mergeAllWindows", "Merge All Project Windows"), + act("window.detachTab", "Move Tab to New Window"), + act("window.nextTab", "Next Project Tab"), + act("window.previousTab", "Previous Project Tab"), + ]); + // ⌘` is macOS's window cycling; elsewhere Ctrl+` is Quick Switch Scheme and the keymap's + // Ctrl+Alt+] / Ctrl+Alt+[ switch windows. + if mac { + window.extend([ + accel("window.next", "Next Project Window", "Cmd+`"), + accel("window.previous", "Previous Project Window", "Cmd+Shift+`"), + ]); + } else { + window.extend([act("window.next", "Next Project Window"), act("window.previous", "Previous Project Window")]); + } + if mac { + window.extend([SEP, Entry::Native(Native::BringAllToFront)]); + } + menus.push(sub("window", "Window", window)); + + let mut help = vec![ + act("navigate.findAction", "Find Action…"), + act("help.keymapReference", "Keymap Reference"), + SEP, + act("app.whatsNew", "What's New"), + act("help.showLog", show_log), + ]; + if !mac { + help.extend([act("app.checkForUpdates", "Check for Updates…"), SEP, act("app.about", "About OpenIDEA")]); + } + menus.push(sub("help", "Help", help)); + menus +} + +/// What a clicked menu item asks the frontend to do. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct MenuRoute { + pub action: String, + pub arg: Option, +} + +/// Maps a clicked item id to the action to run. `None` for ids that are not +/// IDE items (native roles, placeholders). +pub fn route(spec: &[Entry], id: &str) -> Option { + if let Some(path) = id.strip_prefix(RECENT_PREFIX) { + return Some(MenuRoute { action: OPEN_RECENT_ACTION.into(), arg: Some(path.into()) }); + } + if let Some(rest) = id.strip_prefix(DYNAMIC_PREFIX) { + let (action, arg) = match rest.split_once('|') { + Some((action, arg)) => (action, Some(arg.to_owned())), + None => (rest, None), + }; + return (!action.is_empty()).then(|| MenuRoute { action: action.into(), arg }); + } + action_ids(spec).into_iter().any(|a| a == id).then(|| MenuRoute { action: id.into(), arg: None }) +} + +/// `entries` without the action `id` (and a separator it leaves doubled or trailing). +pub fn without_action(entries: Vec, id: &str) -> Vec { + let mut out: Vec = Vec::with_capacity(entries.len()); + for e in entries { + match e { + Entry::Action { id: a, .. } if a == id => {} + Entry::Submenu { id: sid, label, children } => { + out.push(Entry::Submenu { id: sid, label, children: without_action(children, id) }) + } + Entry::Separator if matches!(out.last(), None | Some(Entry::Separator)) => {} + e => out.push(e), + } + } + if matches!(out.last(), Some(Entry::Separator)) { + out.pop(); + } + out +} + +/// Every action id reachable from the spec (with duplicates). +pub fn action_ids(spec: &[Entry]) -> Vec<&'static str> { + fn walk(entries: &[Entry], out: &mut Vec<&'static str>) { + for e in entries { + match e { + Entry::Submenu { children, .. } => walk(children, out), + Entry::Action { id, .. } => out.push(id), + _ => {} + } + } + } + let mut out = Vec::new(); + walk(spec, &mut out); + out +} + +/// Localised labels and keymap accelerators, pushed by the frontend. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct MenuConfig { + pub locale: String, + /// `menu.` → label (ids of submenus, actions and `native.*` roles). + pub labels: HashMap, + /// Action id → native accelerator of its first keymap binding, e.g. `Shift+Meta+O`. + /// Absent when that binding has no native form (chord, double modifier). + pub accelerators: HashMap, + /// [`Entry::Dynamic`] slot → its items, already localised. + #[serde(default)] + pub dynamic: HashMap>, + /// Ids of the toggle actions currently on. + #[serde(default)] + pub checked: Vec, +} + +/// An item of a frontend-listed menu slot. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DynamicItem { + pub action: String, + pub arg: Option, + pub label: String, + /// Drawn with a check mark in this state; `None` for a plain item. + #[serde(default)] + pub checked: Option, +} + +impl DynamicItem { + /// Native menu item id, decoded again by [`route`]. + pub fn item_id(&self) -> String { + match &self.arg { + Some(arg) => format!("{DYNAMIC_PREFIX}{}|{arg}", self.action), + None => format!("{DYNAMIC_PREFIX}{}", self.action), + } + } + + pub fn model(&self) -> MenuNode { + MenuNode::Action { + id: self.action.clone(), + label: self.label.clone(), + hint: None, + arg: self.arg.clone(), + checked: self.checked, + } + } +} + +pub struct LayoutMenu<'a> { + pub id: String, + pub name: &'a str, + pub current: bool, + pub items: Vec>, +} + +impl MenuConfig { + pub fn label(&self, id: &str, default: &str) -> String { + self.labels.get(&format!("menu.{id}")).cloned().unwrap_or_else(|| default.to_owned()) + } + + pub fn dynamic_items(&self, slot: &str) -> &[DynamicItem] { + self.dynamic.get(slot).map(Vec::as_slice).unwrap_or_default() + } + + pub fn layout_menus(&self) -> Vec> { + self.dynamic_items(DYNAMIC_LAYOUTS) + .iter() + .filter_map(|layout| { + let name = layout.arg.as_deref()?; + let current = layout.checked.unwrap_or_default(); + let command = |action: &str, label_key, fallback| { + Some(DynamicItem { + action: action.into(), + arg: Some(name.into()), + label: self.label(label_key, fallback), + checked: None, + }) + }; + let mut items = if current { + vec![ + command("layout.restore", "layout.restoreNamed", "Restore"), + command("layout.saveCurrent", "layout.saveNamed", "Save Changes"), + ] + } else { + vec![command("layout.restore", "layout.applyNamed", "Apply")] + }; + items.extend([ + command("layout.rename", "layout.renameNamed", "Rename…"), + None, + command("layout.delete", "layout.deleteNamed", "Delete…"), + ]); + Some(LayoutMenu { id: format!("layout:{name}"), name, current, items }) + }) + .collect() + } + + /// The keymap accelerator shown on the item of action `id`. + pub fn accelerator(&self, id: &str) -> Option<&str> { + self.accelerators.get(id).map(String::as_str).filter(|a| !a.is_empty()) + } + + /// A dynamic item's accelerator: the action's, unless the item carries an argument. + pub fn dynamic_accelerator(&self, item: &DynamicItem) -> Option<&str> { + item.arg.is_none().then(|| self.accelerator(&item.action)).flatten() + } + + /// Item text: the label, with the spec's hint after a tab (Windows/Linux edit items). + pub fn item_text(&self, id: &str, default: &str, hint: Option<&str>) -> String { + let label = self.label(id, default); + match hint { + Some(hint) => format!("{label}\t{hint}"), + None => label, + } + } +} + +/// A recent Remote Development project (SSH, WSL, Dev Container), kept by the frontend: Open +/// Recent lists it among the local projects, as Manage Projects does. +#[derive(Debug, Clone, PartialEq, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct RemoteRecent { + /// `ssh://host/path`, `wsl://Ubuntu/path`…: what `file.openRecentProject` gets back. + pub location: String, + pub name: String, + /// Where it lives, as shown after the name (`me@host:/srv/app`). + pub detail: String, + pub opened_at_ms: f64, +} + +pub struct RecentItem { + pub path: String, + pub label: String, +} + +/// The local and remote recent projects, most recently opened first. +pub fn recent_items( + recent: &[ide_workspace::RecentProject], + remote: &[RemoteRecent], + home: Option<&Path>, +) -> Vec { + let local = recent.iter().map(|p| { + let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) { + Some(rest) => format!("~/{}", rest.display()), + None => p.path.display().to_string(), + }; + let item = + RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) }; + (p.opened_at_ms, item) + }); + let remote = remote.iter().map(|r| { + (r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) }) + }); + let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect(); + // Stable: the local list's own order holds among equal times. + items.sort_by(|a, b| b.0.total_cmp(&a.0)); + items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect() +} + +/// A menu entry for a menu bar drawn by the frontend (Windows title bar). +/// Labels are the English defaults; the frontend localises them like the native menu. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase", tag = "kind")] +pub enum MenuNode { + Submenu { + id: String, + label: String, + /// Saved layout selection, unset for ordinary submenus. + #[serde(skip_serializing_if = "Option::is_none")] + current: Option, + children: Vec, + }, + /// Runs `id` with `arg`. Items with an `arg` (Open Recent) carry their final label. + /// `checked` is the state of a frontend-listed toggle (Status Bar Widgets). Spec toggles + /// leave it unset: the frontend menu reads their state from the action (`toggled`), the + /// source [`MenuConfig::checked`] is built from for the native menu. + Action { + id: String, + label: String, + hint: Option, + arg: Option, + checked: Option, + }, + /// A disabled placeholder such as "No Recent Projects". + Placeholder { + id: String, + label: String, + }, + Separator, +} + +/// The spec as [`MenuNode`]s; native role items (macOS only) are left out. +pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec { + let mut out = Vec::new(); + for e in spec { + match e { + Entry::Submenu { id, label, children } => out.push(MenuNode::Submenu { + id: (*id).into(), + label: (*label).into(), + current: None, + children: model(children, recent, config), + }), + Entry::Dynamic(DYNAMIC_LAYOUTS) => { + let layouts = config.layout_menus(); + if !layouts.is_empty() { + out.push(MenuNode::Separator); + } + out.extend(layouts.into_iter().map(|layout| { + MenuNode::Submenu { + id: layout.id, + label: layout.name.into(), + current: Some(layout.current), + children: layout + .items + .into_iter() + .map(|item| item.map_or(MenuNode::Separator, |item| item.model())) + .collect(), + } + })); + } + Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => { + let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD); + if !items.is_empty() { + out.push(MenuNode::Submenu { + id: FLUTTER_BUILD_MENU.into(), + label: "Flutter".into(), + current: None, + children: items.iter().map(DynamicItem::model).collect(), + }); + out.push(MenuNode::Separator); + } + } + Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(DynamicItem::model)), + Entry::Action { id, label, hint, .. } => out.push(MenuNode::Action { + id: (*id).into(), + label: (*label).into(), + hint: hint.map(Into::into), + arg: None, + checked: None, + }), + Entry::Native(_) => {} + Entry::Separator => out.push(MenuNode::Separator), + Entry::RecentProjects if recent.is_empty() => { + out.push(MenuNode::Placeholder { id: "recent.none".into(), label: "No Recent Projects".into() }) + } + Entry::RecentProjects => out.extend(recent.iter().map(|r| MenuNode::Action { + id: OPEN_RECENT_ACTION.into(), + label: r.label.clone(), + hint: None, + arg: Some(r.path.clone()), + checked: None, + })), + } + } + out +} diff --git a/crates/ide-host/src/ops/project.rs b/crates/ide-host/src/ops/project.rs index 3cd4cf6ed7..b4011225b7 100644 --- a/crates/ide-host/src/ops/project.rs +++ b/crates/ide-host/src/ops/project.rs @@ -282,6 +282,36 @@ fn refresh_workspace(project: &Project) { project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() }); } +/// Records `project` in `recent` (its branch, unless attached to a workspace, and display name). +pub fn record_recent(recent: &ide_workspace::RecentProjects, project: &Project) -> IdeResult<()> { + let info = info(project); + let attached = info.workspace.as_ref().is_some_and(|w| !w.is_container(&project.root)); + let branch = if attached { + None + } else { + project.repos.read().primary().and_then(|r| r.branch_info().ok()).and_then(|b| b.head) + }; + recent.touch(&project.root, branch)?; + recent.rename(&project.root, Some(&info.display_name))?; + Ok(()) +} + +/// File › Rename Project…: the display name of `window`'s project; an empty `name` restores the +/// folder name. A workspace container renames the workspace, else it is stored in project settings. +pub fn rename(host: &Host, window: &str, name: &str) -> IdeResult> { + let project = host.project(window)?; + let name = name.trim(); + if let Some(workspace) = ide_workspace::workspace::Workspace::load(&project.root)? + && workspace.is_container(&project.root) + { + save_workspace(host, window, name, workspace.projects)?; + } else { + let value = if name.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(name.to_owned()) }; + project.settings.set(SettingsScope::Project, "general.projectName", value)?; + } + Ok(project) +} + /// Attaches a trusted folder without replacing the current project. pub fn attach_workspace(host: &Host, window: &str, path: &Path) -> IdeResult { let project = host.project(window)?; diff --git a/crates/ide-host/src/rpc.rs b/crates/ide-host/src/rpc.rs index 98c84d72f1..49d4999a50 100644 --- a/crates/ide-host/src/rpc.rs +++ b/crates/ide-host/src/rpc.rs @@ -77,6 +77,31 @@ pub struct ChannelMessage { pub data: Value, } +/// Streaming lifecycle signal delivered through a [`ChannelSink`]. +#[derive(Debug, Clone)] +pub enum ChannelSignal { + /// Emitted when a command claims a `{ "$channel": id }` argument. + Opened(u64), + /// One serialized streaming payload. + Data(ChannelMessage), + /// Emitted automatically when the last clone of the command's channel emitter is dropped. + End(u64), +} + +/// Delivers streaming values and lifecycle signals from a command back to its caller. +pub type ChannelSink = Arc; + +struct ChannelDropGuard { + id: u64, + sink: ChannelSink, +} + +impl Drop for ChannelDropGuard { + fn drop(&mut self) { + (self.sink)(ChannelSignal::End(self.id)); + } +} + /// Holds the active client [`Peer`]: once for `--stdio` ([`OnceLock`]) or /// rebound across client reconnects for a persistent daemon ([`PeerSlot`]). pub trait PeerHandle: Send + Sync + 'static { @@ -141,7 +166,7 @@ pub struct Call { pub host: Arc, pub window: String, pub args: Value, - peer: Arc, + channel_sink: ChannelSink, } impl Call { @@ -165,19 +190,26 @@ impl Call { .and_then(|v| v.get("$channel")) .and_then(Value::as_u64) .ok_or_else(|| IdeError::invalid(format!("argument {name}: expected a channel")))?; - let peer = self.peer.clone(); - Ok(Arc::new(move |data: T| { - let Some(peer) = peer.current() else { return }; - match serde_json::to_value(&data) { - Ok(data) => { - let _ = peer.notify("channel", ChannelMessage { id, data }); - } - Err(e) => tracing::warn!("channel {id}: {e}"), - } + let sink = self.channel_sink.clone(); + sink(ChannelSignal::Opened(id)); + let guard = ChannelDropGuard { id, sink }; + Ok(Arc::new(move |data: T| match serde_json::to_value(&data) { + Ok(data) => (guard.sink)(ChannelSignal::Data(ChannelMessage { id: guard.id, data })), + Err(e) => tracing::warn!("channel {}: {e}", guard.id), })) } } +fn peer_channel_sink(peer: Arc) -> ChannelSink { + Arc::new(move |signal: ChannelSignal| { + if let ChannelSignal::Data(msg) = signal + && let Some(peer) = peer.current() + { + let _ = peer.notify("channel", msg); + } + }) +} + type BoxFuture = Pin + Send>>; type HandlerFn = Arc BoxFuture> + Send + Sync>; @@ -188,24 +220,45 @@ pub struct Dispatcher { } impl Dispatcher { - pub fn add(&mut self, name: &'static str, trust: TrustClass, f: F) -> &mut Self + fn wrap_handler(f: F) -> HandlerFn where F: Fn(Call) -> Fut + Send + Sync + 'static, Fut: Future> + Send + 'static, T: Serialize, { let f = Arc::new(f); - let handler: HandlerFn = Arc::new(move |call| { + Arc::new(move |call| { let fut = f(call); Box::pin(async move { let value = fut.await?; serde_json::to_value(value).map_err(|e| IdeError::internal(e.to_string())) }) - }); + }) + } + + pub fn add(&mut self, name: &'static str, trust: TrustClass, f: F) -> &mut Self + where + F: Fn(Call) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + T: Serialize, + { + let handler = Self::wrap_handler(f); assert!(self.handlers.insert(name, (trust, handler)).is_none(), "command {name} is registered twice"); self } + /// Registers or replaces `name` (used by the web server to add shell-level hooks such as recent-project tracking). + pub fn replace(&mut self, name: &'static str, trust: TrustClass, f: F) -> &mut Self + where + F: Fn(Call) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + T: Serialize, + { + let handler = Self::wrap_handler(f); + self.handlers.insert(name, (trust, handler)); + self + } + pub fn commands(&self) -> Vec<&'static str> { let mut out: Vec<_> = self.handlers.keys().copied().collect(); out.sort_unstable(); @@ -223,6 +276,23 @@ impl Dispatcher { ops::register_domains(&mut d); d } + + /// Invokes a command asynchronously with trust enforcement and a caller-supplied channel sink. + pub async fn invoke( + &self, + host: Arc, + window: String, + cmd: &str, + args: Value, + channel_sink: ChannelSink, + ) -> IdeResult { + let Some((trust, handler)) = self.handlers.get(cmd).cloned() else { + return Err(IdeError::unavailable(format!("command {cmd} is not available"))); + }; + host.authorize(&window, trust)?; + let call = Call { host, window, args, channel_sink }; + handler(call).await + } } /// Serves `host` over `reader` / `writer` until the client disconnects. @@ -346,7 +416,7 @@ struct ServerHandler { daemon: Option<(ide_core::CancellationToken, RemoteIdlePolicy)>, } -fn server_info(idle_policy: Option) -> ServerInfo { +pub(crate) fn server_info(idle_policy: Option) -> ServerInfo { ServerInfo { version: env!("CARGO_PKG_VERSION").into(), protocol: PROTOCOL_VERSION, @@ -378,7 +448,12 @@ impl Handler for ServerHandler { return Err((codes::METHOD_NOT_FOUND, format!("command {} is not available remotely", call.cmd))); }; self.host.authorize(&call.window, trust).map_err(error_reply)?; - let c = Call { host: self.host.clone(), window: call.window, args: call.args, peer: self.peer.clone() }; + let c = Call { + host: self.host.clone(), + window: call.window, + args: call.args, + channel_sink: peer_channel_sink(self.peer.clone()), + }; // Requests run on blocking-capable threads: wait for the command here. self.host.runtime.block_on(handler(c)).map_err(error_reply) } diff --git a/crates/ide-host/src/web_server/commands.rs b/crates/ide-host/src/web_server/commands.rs new file mode 100644 index 0000000000..ae0dd4222d --- /dev/null +++ b/crates/ide-host/src/web_server/commands.rs @@ -0,0 +1,502 @@ +//! Shell-level commands registered in web server mode alongside `Dispatcher::standard()`. +//! +//! Project-host commands (`#[command]`) already live in `ide-host::ops` and are served directly. +//! This module supplies the web equivalents of desktop shell commands (`app_info`, `languages`, +//! `recent_projects`, `window_take_launch`, `menu_model`, `light_edit_open`, workspace helpers, +//! HTTP client helpers, and benign no-ops for native-window-only commands). + +use crate::Host; +use crate::catalogue::TrustClass::{self, Always, Trusted}; +use crate::menu; +use crate::ops::project::ProjectInfo; +use crate::rpc::Dispatcher; +use ide_core::settings::Settings; +use ide_core::{IdeError, IpcPath, RequestId}; +use ide_language::LanguageInfo; +use ide_workspace::{RecentProject, RecentProjectGroup, RecentProjects}; +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Arc; + +/// Shared state for shell-level commands in a web server process. +pub struct WebShellState { + pub recent: RecentProjects, + /// Per-window pending launch (taken once by `window_take_launch`). + launches: Mutex>, + /// Default workspace directory configured via `--project` / `OPENIDEA_WORKSPACE_DIR`. + default_project: Option, + /// Whether the default project should be auto-trusted on startup. + trust_default_project: bool, +} + +impl WebShellState { + pub fn new(config_dir: &std::path::Path, default_project: Option, trust_default_project: bool) -> Self { + Self { + recent: RecentProjects::load(config_dir), + launches: Mutex::new(HashMap::new()), + default_project, + trust_default_project, + } + } + + /// Seeds a pending project launch for `window` (from URL `?project=...` or `--project`), + /// or the project the window already has open when its page reloads. + pub fn seed_launch(&self, host: &Host, window: &str, requested_project: Option) { + if let Ok(project) = host.project(window) { + // A reloaded page gets the project the window still has: reopening it keeps its + // index, language servers and runs. + if !project.light { + self.launches.lock().insert(window.to_owned(), project.root.clone()); + } + return; + } + let target = requested_project.or_else(|| self.default_project.clone()); + if let Some(path) = target { + if self.trust_default_project + && self.default_project.as_ref().is_some_and(|p| p == &path) + && let Err(e) = host.trust.inherit(&path) + { + tracing::warn!("cannot trust {}: {e}", path.display()); + } + self.launches.lock().insert(window.to_owned(), path); + } + } + + pub fn take_launch(&self, window: &str) -> Option { + self.launches.lock().remove(window) + } + + pub fn record_project(&self, project: &crate::Project) { + if !project.light + && let Err(e) = crate::ops::project::record_recent(&self.recent, project) + { + tracing::warn!("cannot record {} in recent projects: {e}", project.root.display()); + } + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct AppInfo { + version: String, + platform: String, + windows_build_number: Option, + config_dir: IpcPath, + data_dir: IpcPath, + wayland: bool, + window_buttons: ide_core::platform::WindowButtonLayout, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct BuildInfo { + version: String, + build: String, + profile: String, + os: String, + arch: String, + tauri: String, + updates: bool, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct CloseContext { + quitting: bool, + windows: u32, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct OpenProject { + name: String, + root: PathBuf, + current: bool, + remote: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct LocalDataInfo { + current: String, + default_dir: String, + custom_root: Option, + env_override: bool, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct LogLocation { + dir: IpcPath, + file: Option, +} + +/// The menu bar the browser draws: the desktop spec as on Windows and Linux, without the +/// update check (updates are managed with the server). +fn web_menu_model(recent: &[RecentProject]) -> Vec { + let spec = menu::without_action(menu::spec(menu::Os::Linux), "app.checkForUpdates"); + menu::model(&spec, &menu::recent_items(recent, &[], dirs::home_dir().as_deref()), &menu::MenuConfig::default()) +} + +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +enum LogLevel { + Error, + Warn, + Info, + Debug, +} + +/// Registers all web-mode shell commands onto `dispatcher` (which should already contain +/// `Dispatcher::standard()`). +pub fn register(dispatcher: &mut Dispatcher, shell: Arc) { + // Wrap `open_project` so opened projects are recorded in RecentProjects. + let s = shell.clone(); + dispatcher.replace("open_project", TrustClass::Always, move |c| { + let s = s.clone(); + async move { + let path: PathBuf = c.arg("path")?; + let project = crate::ops::project::open(&c.host, &c.window, &path).await?; + s.record_project(&project); + Ok(crate::ops::project::info(&project)) + } + }); + + // App info & metadata. + dispatcher.add("app_info", TrustClass::Always, |c| async move { + Ok(AppInfo { + version: env!("CARGO_PKG_VERSION").into(), + platform: std::env::consts::OS.into(), + windows_build_number: None, + config_dir: c.host.config_dir.clone().into(), + data_dir: c.host.data_dir.clone().into(), + wayland: false, + window_buttons: ide_core::platform::WindowButtonLayout { left: vec![], right: vec![] }, + }) + }); + + dispatcher.add("app_build_info", TrustClass::Always, |_| async move { + Ok(BuildInfo { + version: env!("CARGO_PKG_VERSION").into(), + build: option_env!("OPENIDEA_BUILD").unwrap_or("web").into(), + profile: if cfg!(debug_assertions) { "debug" } else { "release" }.into(), + os: std::env::consts::OS.into(), + arch: std::env::consts::ARCH.into(), + tauri: "web".into(), + updates: false, + }) + }); + + dispatcher.add("app_log_location", TrustClass::Always, |c| async move { + Ok(LogLocation { dir: c.host.local_data_dir.join("logs").into(), file: None }) + }); + + dispatcher.add("app_update_status", TrustClass::Always, |_| async move { + Ok(json!({ "lastChecked": null, "checking": false })) + }); + dispatcher.add("app_update_announcement", TrustClass::Always, |_| async move { Ok(false) }); + dispatcher.add("app_update_window_ready", TrustClass::Always, |_| async move { Ok(Value::Null) }); + dispatcher.add("app_check_update", TrustClass::Always, |_| async move { + Err::(IdeError::unavailable("Software updates are managed externally in web server mode")) + }); + dispatcher.add("app_release_notes", TrustClass::Always, |_| async move { Ok(Value::Null) }); + dispatcher.add("app_quit", TrustClass::Always, |_| async move { Ok(Value::Null) }); + dispatcher.add("app_cancel_quit", TrustClass::Always, |_| async move { Ok(Value::Null) }); + dispatcher.add("app_restart", TrustClass::Always, |_| async move { Ok(Value::Null) }); + + dispatcher.add("languages", TrustClass::Always, |c| async move { + Ok(c.host.languages.all().iter().map(LanguageInfo::from).collect::>()) + }); + + dispatcher.add("log_frontend", TrustClass::Always, |c| async move { + let level: LogLevel = c.arg("level")?; + let message: String = c.arg("message")?; + match level { + LogLevel::Error => tracing::error!(target: "frontend", "{message}"), + LogLevel::Warn => tracing::warn!(target: "frontend", "{message}"), + LogLevel::Info => tracing::info!(target: "frontend", "{message}"), + LogLevel::Debug => tracing::debug!(target: "frontend", "{message}"), + } + Ok(Value::Null) + }); + + // Recent projects & groups. + let s = shell.clone(); + dispatcher.add("recent_projects", TrustClass::Always, move |c| { + let s = s.clone(); + async move { + let items = s.recent.list(); + c.host + .blocking(move || Ok(ide_workspace::recent::with_live_branches(items))) + .await + .or_else(|_| Ok(s.recent.list())) + } + }); + + let s = shell.clone(); + dispatcher.add("remove_recent_project", TrustClass::Always, move |c| { + let s = s.clone(); + async move { + let path: PathBuf = c.arg("path")?; + s.recent.remove(&path)?; + Ok(Value::Null) + } + }); + + let s = shell.clone(); + dispatcher.add("recent_project_groups", TrustClass::Always, move |_| { + let s = s.clone(); + async move { Ok(s.recent.groups()) } + }); + + let s = shell.clone(); + dispatcher.add("set_recent_project_groups", TrustClass::Always, move |c| { + let s = s.clone(); + async move { + let groups: Vec = c.arg("groups")?; + s.recent.set_groups(groups) + } + }); + + // LightEdit. + dispatcher.add("light_edit_open", TrustClass::Always, |c| async move { + let path: PathBuf = c.arg("path")?; + let (host, window) = (c.host.clone(), c.window.clone()); + let project = c.host.blocking(move || host.open_light(&window, &path)).await?; + Ok::(project.settings.effective()) + }); + + dispatcher.add("light_edit_open_untitled", TrustClass::Always, |c| async move { + let (host, window) = (c.host.clone(), c.window.clone()); + let project = c.host.blocking(move || host.open_light_empty(&window)).await?; + Ok::(project.settings.effective()) + }); + + // Project rename & trust locations. + let s = shell.clone(); + dispatcher.add("project_rename", TrustClass::Always, move |c| { + let s = s.clone(); + async move { + let name: String = c.arg("name")?; + let project = crate::ops::project::rename(&c.host, &c.window, &name)?; + s.record_project(&project); + Ok::(crate::ops::project::info(&project)) + } + }); + + dispatcher.add("project_trust_add_location", TrustClass::Always, |c| async move { + let path: PathBuf = c.arg("path")?; + c.host.trust.add_location(&path)?; + Ok(Value::Null) + }); + + // Launch & window lifecycle. + let s = shell.clone(); + dispatcher.add("window_take_launch", TrustClass::Always, move |c| { + let s = s.clone(); + async move { + let Some(project) = s.take_launch(&c.window) else { + return Ok(Value::Null); + }; + Ok(json!({ + "project": IpcPath::from(project), + "files": [], + "remote": null, + "settingsPage": null, + "newProjects": false, + "positions": [], + "comparison": null, + "diffWindow": null, + "diff": null, + "diffBeforeFiles": false, + "deployment": null, + "editor": null + })) + } + }); + + dispatcher.add("window_complete_launch", TrustClass::Always, |_| async move { Ok(Value::Null) }); + + dispatcher.add("window_open_projects", TrustClass::Always, |c| async move { + let current_root = c.host.project(&c.window).ok().filter(|p| !p.light).map(|p| p.root.clone()); + let list: Vec = c + .host + .projects() + .into_iter() + .filter(|p| !p.light) + .map(|p| OpenProject { + name: p.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), + current: current_root.as_ref() == Some(&p.root), + root: p.root.clone(), + remote: None, + }) + .collect(); + Ok(list) + }); + + dispatcher.add("window_open_project", TrustClass::Always, |_| async move { Ok(json!({ "kind": "current" })) }); + + dispatcher.add("window_open_files", TrustClass::Always, |c| async move { + let files: Vec = c.arg("files")?; + Ok(files) + }); + + dispatcher.add("window_is_fullscreen", TrustClass::Always, |_| async move { Ok(false) }); + dispatcher.add("window_close_context", TrustClass::Always, |_| async move { + Ok(CloseContext { quitting: false, windows: 1 }) + }); + for (noop, trust) in [ + ("window_set_titlebar_height", Always), + ("window_set_smooth_scrolling", Always), + ("window_flash_taskbar", Always), + ("window_cycle", Always), + ("menu_configure", Always), + ("menu_refresh", Always), + ("menu_set_disabled", Always), + ("show_system_notification", Trusted), + ("window_group_cancel_close", Always), + ("window_group_restore", Always), + ("plugin_subscribe", Always), + ("plugin_activation_event", Trusted), + ("plugin_set_theme_frame", Always), + ] { + dispatcher.add(noop, trust, |_| async move { Ok(Value::Null) }); + } + for (noop_false, trust) in [ + ("window_toggle_fullscreen", Always), + ("window_toggle_zoom", Always), + ("window_start_drag", Always), + ("window_drag_files", Always), + ("file_dialog_needs_gtk", Trusted), + ("clipboard_has_files", Always), + ("clipboard_has_image", Always), + ] { + dispatcher.add(noop_false, trust, |_| async move { Ok(false) }); + } + + let s = shell.clone(); + dispatcher.add("menu_model", TrustClass::Always, move |_| { + let s = s.clone(); + async move { Ok(web_menu_model(&s.recent.list())) } + }); + + // Empty desktop-only collections so UI components render cleanly without errors. + for (empty_list, trust) in [ + ("window_group_current", Always), + ("system_font_families", Always), + ("system_probe_hotkeys", Trusted), + ("wsl_distros", Always), + ("web_browsers", Always), + ("plugin_catalog", Always), + ("plugin_installed_intellij_themes", Always), + ("git_credentials", Always), + ("android_devices", Trusted), + ("clipboard_file_list", Always), + ] { + dispatcher.add(empty_list, trust, |_| async move { Ok(Vec::::new()) }); + } + + for (null_opt, trust) in [ + ("wsl_resolve", Always), + ("remote_current", Always), + ("plugin_market_url", Always), + ("clipboard_text", Trusted), + ("clipboard_image", Always), + ] { + dispatcher.add(null_opt, trust, |_| async move { Ok(Value::Null) }); + } + + dispatcher.add("plugin_list", TrustClass::Always, |_| async move { + Ok(json!({ "plugins": [], "activeTheme": null, "ui": [] })) + }); + + // Caches & LSP & Web & Workspace & HTTP helpers already available through ide-host dependencies. + dispatcher.add("caches_local_data_info", TrustClass::Trusted, |c| async move { + let current = c.host.local_data_dir.to_string_lossy().into_owned(); + Ok(LocalDataInfo { + default_dir: current.clone(), + current, + custom_root: None, + env_override: std::env::var_os("OPENIDEA_SERVER_HOME").is_some(), + }) + }); + + dispatcher.add("caches_schedule_invalidation", TrustClass::Always, |_| async move { Ok(Value::Null) }); + + dispatcher.add("lsp_restart_named", TrustClass::Trusted, |c| async move { + let name: String = c.arg("name")?; + crate::ops::lsp::lsp_restart_named(&c.host, &name).await?; + Ok(Value::Null) + }); + + dispatcher.add("web_serves_page", TrustClass::Trusted, |c| async move { + let url: String = c.arg("url")?; + Ok(crate::ops::web::serves_page(&url).await) + }); + + dispatcher.add("workspace_discover_projects", TrustClass::Always, |c| async move { + let request: RequestId = c.arg("request")?; + let folders: Vec = c.arg("folders")?; + let cancel = c.host.begin_request(request); + let result = c.host.blocking(move || ide_workspace::project_discovery::discover(folders, &cancel)).await; + c.host.end_request(request); + result + }); + + dispatcher.add("workspace_create", TrustClass::Always, |c| async move { + let path: PathBuf = c.arg("path")?; + let name: String = c.arg("name")?; + let projects: Vec = c.arg("projects")?; + c.host + .blocking(move || { + ide_workspace::workspace::Workspace::save(&path, &name, projects, true)?; + Ok(IpcPath::from(dunce::canonicalize(path)?)) + }) + .await + }); + + let s = shell.clone(); + dispatcher.add("workspace_update", TrustClass::Always, move |c| { + let s = s.clone(); + async move { + let name: String = c.arg("name")?; + let projects: Vec = c.arg("projects")?; + let (host, window) = (c.host.clone(), c.window.clone()); + let info = + c.host.blocking(move || crate::ops::project::save_workspace(&host, &window, &name, projects)).await?; + if let Ok(project) = c.host.project(&c.window) { + s.record_project(&project); + } + Ok(info) + } + }); + + let s = shell.clone(); + dispatcher.add("workspace_attach", TrustClass::Always, move |c| { + let s = s.clone(); + async move { + let path: PathBuf = c.arg("path")?; + let (host, window) = (c.host.clone(), c.window.clone()); + let root = c.host.blocking(move || crate::ops::project::attach_workspace(&host, &window, &path)).await?; + if let Ok(project) = c.host.project(&c.window) { + s.record_project(&project); + } + Ok(root) + } + }); + + dispatcher.add("http_requests", TrustClass::Trusted, |c| async move { + let text: String = c.arg("text")?; + Ok(ide_http::parse::requests(&text)) + }); + + dispatcher.add("http_from_curl", TrustClass::Trusted, |c| async move { + let command: String = c.arg("command")?; + Ok(ide_http::curl::from_curl(&command)) + }); + + dispatcher.add("ssh_askpass_answer", TrustClass::Always, |_| async move { Ok(Value::Null) }); +} diff --git a/crates/ide-host/src/web_server/mod.rs b/crates/ide-host/src/web_server/mod.rs new file mode 100644 index 0000000000..23bfbfdecf --- /dev/null +++ b/crates/ide-host/src/web_server/mod.rs @@ -0,0 +1,1736 @@ +//! HTTP + WebSocket web server for running OpenIDEA in a browser on a configurable host and port. +//! +//! Serves the built frontend assets alongside a WebSocket RPC endpoint (`api/ws`) backed by the +//! same [`Host`] and [`Dispatcher`] used by remote development. Designed to work directly and +//! behind reverse proxies regardless of whether the proxy strips or preserves its URL prefix. + +pub mod commands; + +use crate::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND}; +use crate::rpc::{self, ChannelSignal, ChannelSink, Dispatcher, ServerInfo}; +use crate::{Host, HostConfig}; +use bytes::Bytes; +use commands::WebShellState; +use flate2::Compression; +use flate2::write::GzEncoder; +use futures::{SinkExt, StreamExt}; +use http_body_util::{BodyExt, Full}; +use hyper::body::Incoming; +use hyper::header::{self, HeaderValue}; +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use ide_core::{EventSink, IdeError, IdeEvent, IdeResult, RequestId, SharedSink}; +use ide_language::LanguageRegistry; +use parking_lot::{Mutex, RwLock}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet}; +use std::io::Write as _; +use std::net::SocketAddr; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; +use tokio::net::TcpListener; +use tokio::sync::{mpsc, oneshot}; +use tokio_tungstenite::WebSocketStream; +use tokio_tungstenite::tungstenite::Message as WsMessage; +use tokio_tungstenite::tungstenite::handshake::derive_accept_key; +use tokio_tungstenite::tungstenite::protocol::Role; + +/// Keepalive ping interval so reverse proxies do not drop idle WebSocket sessions. +const WS_PING_INTERVAL: Duration = Duration::from_secs(25); +/// Minimum uncompressed asset size (bytes) before applying gzip compression. +const GZIP_MIN_BYTES: usize = 1024; +const AUTH_COOKIE_NAME: &str = "openidea_token"; +const WEB_META_TAG: &str = r#""#; + +/// Runtime configuration for `openidea-server --web`. +#[derive(Debug, Clone)] +pub struct WebServerConfig { + /// Interface address to bind (e.g. `127.0.0.1` or `0.0.0.0`). + pub host: String, + /// TCP port to listen on (0 lets the OS assign an ephemeral port). + pub port: u16, + /// Optional URL prefix when deployed behind a reverse proxy (e.g. `/ide`). + pub base_path: Option, + /// Directory containing the built frontend (`index.html`, `boot.js`, `assets/`). + pub web_dir: PathBuf, + /// Optional workspace directory opened automatically on first connect. + pub project: Option, + /// Automatically trust `project` for this process without prompting. + pub trust_project: bool, + /// Optional bearer/cookie authentication token; `None` disables authentication. + pub auth_token: Option, +} + +/// Handle to a running web server instance (useful for tests and graceful shutdown). +pub struct RunningWebServer { + pub addr: SocketAddr, + shutdown_tx: Option>, + join: tokio::task::JoinHandle<()>, +} + +impl RunningWebServer { + /// Signals the server to stop accepting connections and shuts down its [`Host`]. + pub async fn shutdown(mut self) { + if let Some(tx) = self.shutdown_tx.take() { + let _ = tx.send(()); + } + let _ = self.join.await; + } +} + +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "camelCase")] +enum ClientMessage { + Hello { + #[serde(default)] + window: Option, + #[serde(default)] + project: Option, + }, + Invoke { + id: u64, + cmd: String, + #[serde(default)] + args: Value, + }, + Ping, +} + +#[derive(Serialize)] +#[serde(tag = "type", rename_all = "camelCase")] +enum ServerMessage { + Ready { + window: String, + /// Changes when the server restarts: the page reloads, as its projects and runs are gone. + instance: String, + server: ServerInfo, + }, + Response { + id: u64, + ok: bool, + #[serde(skip_serializing_if = "Option::is_none")] + data: Option, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option, + }, + Channel { + id: u64, + data: Value, + }, + ChannelEnd { + id: u64, + }, + Event { + window: Option, + event: IdeEvent, + }, + /// Sent to an older browser tab when another tab attaches to the same server window label. + Superseded, + Pong, +} + +type Outbound = mpsc::UnboundedSender; +type Subscriber = (u64, Outbound); + +/// Fans out [`IdeEvent`]s emitted by [`Host`] to active WebSocket connections per window label. +#[derive(Default)] +struct WebEventHub { + next_id: AtomicU64, + /// `window_label` -> active connection sender (single active tab per window to avoid conflicting edits). + subscribers: RwLock>>, +} + +impl WebEventHub { + fn subscribe(&self, window: &str, tx: Outbound) -> u64 { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let displaced = { + let mut map = self.subscribers.write(); + let list = map.entry(window.to_owned()).or_default(); + let prev = std::mem::take(list); + list.push((id, tx)); + prev + }; + for (_, old_tx) in displaced { + let _ = old_tx.send(ServerMessage::Superseded); + } + id + } + + fn unsubscribe(&self, window: &str, conn_id: u64) { + let mut map = self.subscribers.write(); + if let Some(list) = map.get_mut(window) { + list.retain(|(id, _)| *id != conn_id); + if list.is_empty() { + map.remove(window); + } + } + } + + fn emit(&self, window: Option<&str>, event: IdeEvent) { + let map = self.subscribers.read(); + match window { + Some(w) => { + if let Some(list) = map.get(w) { + for (_, tx) in list { + let _ = tx.send(ServerMessage::Event { window: Some(w.to_owned()), event: event.clone() }); + } + } + } + None => { + for (w, list) in map.iter() { + for (_, tx) in list { + let _ = tx.send(ServerMessage::Event { window: Some(w.clone()), event: event.clone() }); + } + } + } + } + } + + fn sink_for(self: &Arc, window: String) -> SharedSink { + Arc::new(HubSink { hub: self.clone(), window }) + } +} + +struct HubSink { + hub: Arc, + window: String, +} + +impl EventSink for HubSink { + fn emit(&self, event: IdeEvent) { + self.hub.emit(Some(&self.window), event); + } +} + +struct ServerState { + host: Arc, + dispatcher: Dispatcher, + shell: Arc, + hub: Arc, + web_dir: PathBuf, + base_path: Option, + auth_token: Option, + instance: String, +} + +/// Starts the web server bound to `config.host:config.port` and returns a handle immediately. +pub async fn start(config: WebServerConfig, base: PathBuf) -> IdeResult { + let (config_dir, data_dir) = (base.join("config"), base.join("data")); + for dir in [&config_dir, &data_dir] { + std::fs::create_dir_all(dir) + .map_err(|e| IdeError::internal(format!("cannot create {}: {e}", dir.display())))?; + } + let web_dir = dunce::canonicalize(&config.web_dir).map_err(|e| { + IdeError::invalid(format!( + "web assets directory {} is not readable: {e} (build the frontend with `pnpm build` or pass --web-dir)", + config.web_dir.display() + )) + })?; + if !web_dir.join("index.html").is_file() { + return Err(IdeError::invalid(format!( + "web assets directory {} does not contain index.html (build the frontend with `pnpm build`)", + web_dir.display() + ))); + } + let languages = LanguageRegistry::load(Some(&config_dir.join("languages"))) + .map(Arc::new) + .map_err(|e| IdeError::internal(format!("language definitions: {e}")))?; + let plugin_languages = RemotePluginLanguages::new(Some(&data_dir)); + languages.attach_plugins(plugin_languages.store().clone()); + + let hub = Arc::new(WebEventHub::default()); + let sink_hub = hub.clone(); + let host = Arc::new(Host::new(HostConfig { + config_dir: config_dir.clone(), + local_data_dir: data_dir.clone(), + data_dir, + languages, + syntax: Arc::default(), + sink_for: Box::new(move |window| sink_hub.sink_for(window.to_owned())), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: true, + })); + host.mcp.set_stdio_link(base.join("bin").join("openidea-server")); + host.mcp_background.serve_none(); + host.mcp.apply(&host); + + if let Some(root) = std::env::var_os(crate::trust::TRUSTED_ROOT_ENV) + && let Err(e) = host.trust.inherit(Path::new(&root)) + { + tracing::warn!("cannot trust {}: {e}", root.to_string_lossy()); + } + + let default_project = config.project.as_ref().map(|p| dunce::canonicalize(p).unwrap_or_else(|_| p.clone())); + if config.trust_project + && let Some(ref root) = default_project + && let Err(e) = host.trust.inherit(root) + { + tracing::warn!("cannot trust {}: {e}", root.display()); + } + + let shell = Arc::new(WebShellState::new(&config_dir, default_project, config.trust_project)); + let mut dispatcher = Dispatcher::standard(); + dispatcher.add(SYNC_COMMAND, crate::catalogue::TrustClass::Trusted, move |c| { + let remote = plugin_languages.clone(); + async move { + let report = remote.sync(c.arg("languages")?); + c.host.plugin_languages_changed(); + Ok(report) + } + }); + commands::register(&mut dispatcher, shell.clone()); + + let bind_addr = format!("{}:{}", config.host, config.port); + let listener = + TcpListener::bind(&bind_addr).await.map_err(|e| IdeError::internal(format!("cannot bind {bind_addr}: {e}")))?; + let addr = listener.local_addr().map_err(|e| IdeError::internal(e.to_string()))?; + + let state = Arc::new(ServerState { + host: host.clone(), + dispatcher, + shell, + hub, + web_dir, + base_path: config.base_path.as_deref().and_then(normalize_base_path), + auth_token: config.auth_token, + instance: generate_token()[..16].to_owned(), + }); + + if state.auth_token.is_none() && !addr.ip().is_loopback() { + tracing::warn!( + "listening on non-loopback address {} without --token authentication; ensure an authenticating reverse proxy sits in front", + addr + ); + } + + let (shutdown_tx, mut shutdown_rx) = oneshot::channel::<()>(); + let join = tokio::spawn(async move { + loop { + tokio::select! { + _ = &mut shutdown_rx => break, + accepted = listener.accept() => { + let (stream, peer_addr) = match accepted { + Ok(pair) => pair, + Err(e) => { + tracing::warn!("accept failed: {e}"); + continue; + } + }; + let state = state.clone(); + tokio::spawn(async move { + let io = TokioIo::new(stream); + let svc = service_fn(move |req| { + let state = state.clone(); + async move { Ok::<_, std::convert::Infallible>(handle_http(req, state).await) } + }); + if let Err(e) = http1::Builder::new().serve_connection(io, svc).with_upgrades().await { + tracing::debug!("HTTP connection {peer_addr} ended: {e}"); + } + }); + } + } + } + host.mcp.stop(&host); + if tokio::time::timeout(Duration::from_secs(10), host.shutdown()).await.is_err() { + tracing::warn!("language servers did not shut down in time"); + } + }); + + Ok(RunningWebServer { addr, shutdown_tx: Some(shutdown_tx), join }) +} + +/// Runs the web server until `SIGINT` or `SIGTERM` is received. +pub async fn run(config: WebServerConfig, base: PathBuf) -> i32 { + let running = match start(config.clone(), base).await { + Ok(r) => r, + Err(e) => { + eprintln!("openidea-server --web: {e}"); + return 1; + } + }; + let prefix = config + .base_path + .as_deref() + .and_then(normalize_base_path) + .map(|p| format!("/{p}/")) + .unwrap_or_else(|| "/".into()); + let display_host = + if running.addr.ip().is_unspecified() { "localhost".to_owned() } else { running.addr.ip().to_string() }; + tracing::info!( + "openidea-server {} web mode listening on http://{}{}", + env!("CARGO_PKG_VERSION"), + running.addr, + prefix + ); + eprintln!("OpenIDEA Web IDE listening on http://{}:{}{}", display_host, running.addr.port(), prefix); + if let Some(ref token) = config.auth_token { + eprintln!("Access URL with token: http://{}:{}{}?token={}", display_host, running.addr.port(), prefix, token); + } + + wait_for_shutdown_signal().await; + tracing::info!("shutting down openidea-server web mode"); + running.shutdown().await; + 0 +} + +async fn wait_for_shutdown_signal() { + #[cfg(unix)] + { + let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).ok(); + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = async { + if let Some(ref mut s) = sigterm { + s.recv().await; + } else { + std::future::pending::<()>().await; + } + } => {} + } + } + #[cfg(not(unix))] + { + let _ = tokio::signal::ctrl_c().await; + } +} + +/// Auto-discovers a built frontend directory (`dist/`) when `--web-dir` is not explicitly given. +pub fn default_web_dir() -> PathBuf { + if let Some(env_dir) = std::env::var_os("OPENIDEA_WEB_DIR") { + return PathBuf::from(env_dir); + } + if let Ok(exe) = std::env::current_exe() + && let Some(dir) = exe.parent() + { + for candidate in [dir.join("dist"), dir.join("../share/openidea/web"), dir.join("../../dist")] { + if candidate.join("index.html").is_file() { + return candidate; + } + } + } + PathBuf::from("dist") +} + +/// Generates a random 24-byte URL-safe hex authentication token. +pub fn generate_token() -> String { + let mut bytes = [0u8; 24]; + let _ = getrandom::fill(&mut bytes); + let mut out = String::with_capacity(48); + for b in bytes { + use std::fmt::Write; + let _ = write!(&mut out, "{b:02x}"); + } + out +} + +fn normalize_base_path(raw: &str) -> Option { + let trimmed = raw.trim().trim_matches('/'); + if trimmed.is_empty() { None } else { Some(trimmed.to_owned()) } +} + +fn strip_base_path<'a>(path: &'a str, base_path: Option<&str>) -> &'a str { + let Some(base) = base_path else { return path }; + let without_slash = path.strip_prefix('/').unwrap_or(path); + if let Some(rest) = without_slash.strip_prefix(base) + && (rest.is_empty() || rest.starts_with('/')) + { + return if rest.is_empty() { "/" } else { rest }; + } + path +} + +fn is_endpoint(path: &str, suffix: &str) -> bool { + let clean = path.trim_end_matches('/'); + clean == suffix || clean.ends_with(suffix) +} + +fn constant_time_eq(a: &str, b: &str) -> bool { + let (a, b) = (a.as_bytes(), b.as_bytes()); + if a.len() != b.len() { + return false; + } + let mut diff = 0u8; + for (&x, &y) in a.iter().zip(b.iter()) { + diff |= x ^ y; + } + diff == 0 +} + +fn query_param(query: Option<&str>, key: &str) -> Option { + for pair in query?.split('&') { + let (k, v) = pair.split_once('=').unwrap_or((pair, "")); + if k == key { + return percent_decode(v); + } + } + None +} + +fn strip_query_param(query: Option<&str>, drop_key: &str) -> String { + let Some(q) = query else { return String::new() }; + let kept: Vec<&str> = q + .split('&') + .filter(|pair| { + let k = pair.split_once('=').map(|(k, _)| k).unwrap_or(pair); + !pair.is_empty() && k != drop_key + }) + .collect(); + if kept.is_empty() { String::new() } else { format!("?{}", kept.join("&")) } +} + +fn cookie_value(req: &Request, name: &str) -> Option { + for val in req.headers().get_all(header::COOKIE) { + let Ok(s) = val.to_str() else { continue }; + for part in s.split(';') { + let Some((k, v)) = part.trim().split_once('=') else { continue }; + if k == name { + return Some(v.to_owned()); + } + } + } + None +} + +fn bearer_token(req: &Request) -> Option<&str> { + let header = req.headers().get(header::AUTHORIZATION)?.to_str().ok()?; + header.strip_prefix("Bearer ").or_else(|| header.strip_prefix("bearer ")) +} + +enum AuthStatus { + Authorized, + QueryTokenValid, + Unauthorized, +} + +fn check_auth(req: &Request, expected: Option<&str>) -> AuthStatus { + let Some(expected) = expected else { return AuthStatus::Authorized }; + if let Some(token) = bearer_token(req) + && constant_time_eq(token, expected) + { + return AuthStatus::Authorized; + } + if let Some(cookie) = cookie_value(req, AUTH_COOKIE_NAME) + && constant_time_eq(&cookie, expected) + { + return AuthStatus::Authorized; + } + if let Some(qtok) = query_param(req.uri().query(), "token") + && constant_time_eq(&qtok, expected) + { + return AuthStatus::QueryTokenValid; + } + AuthStatus::Unauthorized +} + +fn is_https_request(req: &Request) -> bool { + if let Some(proto) = req.headers().get("x-forwarded-proto").and_then(|v| v.to_str().ok()) + && proto.split(',').next().is_some_and(|p| p.trim().eq_ignore_ascii_case("https")) + { + return true; + } + if let Some(fwd) = req.headers().get(header::FORWARDED).and_then(|v| v.to_str().ok()) + && fwd.to_ascii_lowercase().contains("proto=https") + { + return true; + } + false +} + +fn cookie_scope_path(raw_path: &str) -> String { + let mut base = raw_path; + if let Some(stripped) = base.strip_suffix("/api/auth").or_else(|| base.strip_suffix("/api/auth/")) { + base = stripped; + } else if let Some(stripped) = base.strip_suffix("/index.html") { + base = stripped; + } + if base.is_empty() || base.contains([';', '\r', '\n']) { + return "/".into(); + } + let mut out = if base.starts_with('/') { base.to_owned() } else { format!("/{base}") }; + if !out.ends_with('/') { + out.push('/'); + } + out +} + +fn auth_cookie_header(req: &Request, raw_path: &str, token: &str) -> HeaderValue { + let path = cookie_scope_path(raw_path); + let secure = if is_https_request(req) { "; Secure" } else { "" }; + HeaderValue::from_str(&format!("{AUTH_COOKIE_NAME}={token}; Path={path}; HttpOnly; SameSite=Lax{secure}")) + .unwrap_or_else(|_| HeaderValue::from_static("")) +} + +fn normalize_authority(raw: &str, default_port: Option<&str>) -> String { + let trimmed = raw.trim().to_ascii_lowercase(); + if let Some(port) = default_port { + let suffix = format!(":{port}"); + if let Some(stripped) = trimmed.strip_suffix(&suffix) { + return stripped.to_owned(); + } + } + trimmed +} + +/// Validates that a browser WebSocket upgrade request comes from the same host/authority +/// (preventing Cross-Site WebSocket Hijacking). Requests without an `Origin` header (such as +/// CLI tools or tests) are allowed. +fn is_same_origin(origin: Option<&str>, host: Option<&str>, forwarded_host: Option<&str>) -> bool { + let Some(origin) = origin else { return true }; + let origin = origin.trim(); + if origin.is_empty() || origin.eq_ignore_ascii_case("null") { + return false; + } + let Some((scheme, rest)) = origin.split_once("://") else { + return false; + }; + let default_port = match scheme.to_ascii_lowercase().as_str() { + "http" => Some("80"), + "https" => Some("443"), + _ => return false, + }; + let origin_authority = rest.split('/').next().unwrap_or(""); + if origin_authority.is_empty() { + return false; + } + let expected_origin = normalize_authority(origin_authority, default_port); + let matches_host = |candidate: &str| { + candidate.split(',').next().is_some_and(|first| normalize_authority(first, default_port) == expected_origin) + }; + host.is_some_and(matches_host) || forwarded_host.is_some_and(matches_host) +} + +fn text_response(status: StatusCode, content_type: &'static str, body: impl Into) -> Response> { + Response::builder() + .status(status) + .header(header::CONTENT_TYPE, content_type) + .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff") + .body(Full::new(body.into())) + .unwrap() +} + +fn is_websocket_upgrade(req: &Request) -> bool { + let has_upgrade = req + .headers() + .get(header::UPGRADE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.eq_ignore_ascii_case("websocket")); + let has_key = req.headers().contains_key(header::SEC_WEBSOCKET_KEY); + has_upgrade && has_key +} + +async fn handle_http(req: Request, state: Arc) -> Response> { + let raw_path = req.uri().path().to_owned(); + let effective_path = strip_base_path(&raw_path, state.base_path.as_deref()).to_owned(); + + // Unauthenticated health endpoint for container liveness / readiness probes. + if req.method() == Method::GET && is_endpoint(&effective_path, "/api/health") { + let body = json!({ + "status": "ok", + "version": env!("CARGO_PKG_VERSION"), + "protocol": rpc::PROTOCOL_VERSION, + }); + return text_response(StatusCode::OK, "application/json", body.to_string()); + } + + // Token login POST endpoint when auth is enabled. + if req.method() == Method::POST && is_endpoint(&effective_path, "/api/auth") { + return handle_auth_post(req, &raw_path, &state).await; + } + + // WebSocket RPC upgrade endpoint. + if is_endpoint(&effective_path, "/api/ws") && is_websocket_upgrade(&req) { + let origin = req.headers().get(header::ORIGIN).and_then(|v| v.to_str().ok()); + let host = req.headers().get(header::HOST).and_then(|v| v.to_str().ok()); + let fwd_host = req.headers().get("x-forwarded-host").and_then(|v| v.to_str().ok()); + if !is_same_origin(origin, host, fwd_host) { + tracing::warn!("rejected cross-origin WebSocket upgrade (origin={origin:?}, host={host:?})"); + return text_response(StatusCode::FORBIDDEN, "application/json", r#"{"error":"cross-origin rejected"}"#); + } + if matches!(check_auth(&req, state.auth_token.as_deref()), AuthStatus::Unauthorized) { + return text_response(StatusCode::UNAUTHORIZED, "application/json", r#"{"error":"unauthorized"}"#); + } + return handle_ws_upgrade(req, state); + } + + if req.method() != Method::GET && req.method() != Method::HEAD { + return text_response(StatusCode::METHOD_NOT_ALLOWED, "text/plain; charset=utf-8", "Method Not Allowed"); + } + + let head_only = req.method() == Method::HEAD; + let gzip = accepts_gzip(&req); + + // Resolve static assets inside `web_dir` (supporting reverse-proxy subpaths even when rewrite=false). + if let Some((file_path, rel_path)) = resolve_static_asset(&state.web_dir, &effective_path) { + if rel_path != "index.html" { + return serve_static_file(&file_path, &rel_path, head_only, gzip).await; + } + } else if looks_like_asset_path(&effective_path) { + return text_response(StatusCode::NOT_FOUND, "text/plain; charset=utf-8", "Not Found"); + } + + // Entry HTML page: enforce auth if configured. + match check_auth(&req, state.auth_token.as_deref()) { + AuthStatus::Unauthorized => return login_page_response(), + AuthStatus::QueryTokenValid => { + if let Some(ref token) = state.auth_token { + let rest = strip_query_param(req.uri().query(), "token"); + let target = + if raw_path.ends_with('/') { format!("{raw_path}{rest}") } else { format!("{raw_path}/{rest}") }; + return Response::builder() + .status(StatusCode::FOUND) + .header(header::LOCATION, target) + .header(header::SET_COOKIE, auth_cookie_header(&req, &raw_path, token)) + .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff") + .body(Full::new(Bytes::new())) + .unwrap(); + } + } + AuthStatus::Authorized => {} + } + + // Ensure a trailing slash on subpath entry URLs so relative `./boot.js`, `./assets/...`, + // and `api/ws` resolve beneath the reverse-proxy prefix. + if !raw_path.ends_with('/') && !raw_path.ends_with("/index.html") { + let last_segment = raw_path.rsplit('/').next().unwrap_or(""); + if !last_segment.is_empty() { + let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default(); + return Response::builder() + .status(StatusCode::TEMPORARY_REDIRECT) + .header(header::LOCATION, format!("{last_segment}/{query}")) + .body(Full::new(Bytes::new())) + .unwrap(); + } + } + + serve_index_html(&state.web_dir, head_only, gzip).await +} + +async fn handle_auth_post(req: Request, raw_path: &str, state: &ServerState) -> Response> { + let Some(expected) = state.auth_token.as_deref() else { + return text_response(StatusCode::OK, "application/json", r#"{"ok":true}"#); + }; + let cookie_hdr = auth_cookie_header(&req, raw_path, expected); + let body = match req.into_body().collect().await { + Ok(b) => b.to_bytes(), + Err(_) => return text_response(StatusCode::BAD_REQUEST, "text/plain; charset=utf-8", "Bad Request"), + }; + let supplied = serde_json::from_slice::(&body) + .ok() + .and_then(|v| v.get("token").and_then(Value::as_str).map(str::to_owned)) + .or_else(|| { + let text = std::str::from_utf8(&body).ok()?; + query_param(Some(text), "token") + }); + if let Some(token) = supplied + && constant_time_eq(&token, expected) + { + return Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, "application/json") + .header(header::SET_COOKIE, cookie_hdr) + .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff") + .body(Full::new(Bytes::from_static(br#"{"ok":true}"#))) + .unwrap(); + } + text_response(StatusCode::UNAUTHORIZED, "application/json", r#"{"error":"invalid token"}"#) +} + +fn login_page_response() -> Response> { + const HTML: &str = r#" + + + + +OpenIDEA — Sign In + + + +
+

OpenIDEA Web

+

Enter the server access token to continue.

+ + + +
+ + +"#; + Response::builder() + .status(StatusCode::UNAUTHORIZED) + .header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .header(header::CACHE_CONTROL, "no-store") + .body(Full::new(Bytes::from_static(HTML.as_bytes()))) + .unwrap() +} + +fn handle_ws_upgrade(req: Request, state: Arc) -> Response> { + let Some(key) = req.headers().get(header::SEC_WEBSOCKET_KEY).and_then(|v| v.to_str().ok()).map(str::to_owned) + else { + return text_response(StatusCode::BAD_REQUEST, "text/plain; charset=utf-8", "Missing Sec-WebSocket-Key"); + }; + let accept = derive_accept_key(key.as_bytes()); + tokio::spawn(async move { + match hyper::upgrade::on(req).await { + Ok(upgraded) => { + let ws = WebSocketStream::from_raw_socket(TokioIo::new(upgraded), Role::Server, None).await; + serve_ws_session(ws, state).await; + } + Err(e) => tracing::warn!("WebSocket upgrade failed: {e}"), + } + }); + Response::builder() + .status(StatusCode::SWITCHING_PROTOCOLS) + .header(header::UPGRADE, "websocket") + .header(header::CONNECTION, "Upgrade") + .header(header::SEC_WEBSOCKET_ACCEPT, accept) + .body(Full::new(Bytes::new())) + .unwrap() +} + +fn collect_arg_channels(val: &Value, out: &mut Vec) { + match val { + Value::Object(map) => { + if map.len() == 1 + && let Some(id) = map.get("$channel").and_then(Value::as_u64) + { + out.push(id); + return; + } + for v in map.values() { + collect_arg_channels(v, out); + } + } + Value::Array(items) => { + for v in items { + collect_arg_channels(v, out); + } + } + _ => {} + } +} + +async fn serve_ws_session(ws: WebSocketStream, state: Arc) +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static, +{ + let (mut ws_tx, mut ws_rx) = ws.split(); + // Unbounded like the stdio transport's writer: a dropped channel message or event would + // leave a terminal, run console or tool window silently out of step. + let (out_tx, mut out_rx) = mpsc::unbounded_channel::(); + let (superseded_tx, mut superseded_rx) = oneshot::channel::<()>(); + let active_requests: Arc>> = Arc::new(Mutex::new(HashSet::new())); + + // Writer task forwards queued server messages and emits periodic keepalive pings. + let writer = tokio::spawn(async move { + let mut ping = tokio::time::interval(WS_PING_INTERVAL); + ping.tick().await; + let mut superseded_tx = Some(superseded_tx); + loop { + tokio::select! { + msg = out_rx.recv() => { + let Some(msg) = msg else { break }; + let is_superseded = matches!(msg, ServerMessage::Superseded); + match serde_json::to_string(&msg) { + Ok(text) => { + if ws_tx.send(WsMessage::Text(text.into())).await.is_err() { + break; + } + } + Err(e) => tracing::warn!("failed to serialize WebSocket message: {e}"), + } + if is_superseded { + let _ = ws_tx.send(WsMessage::Close(None)).await; + if let Some(tx) = superseded_tx.take() { + let _ = tx.send(()); + } + break; + } + } + _ = ping.tick() => { + if ws_tx.send(WsMessage::Ping(Bytes::new())).await.is_err() { + break; + } + } + } + } + }); + + let mut window_label: Option = None; + let mut sub_id: Option = None; + + loop { + let frame = tokio::select! { + _ = &mut superseded_rx => break, + next = ws_rx.next() => match next { + Some(f) => f, + None => break, + }, + }; + let msg = match frame { + Ok(WsMessage::Text(text)) => text, + Ok(WsMessage::Ping(_)) | Ok(WsMessage::Pong(_)) => continue, + Ok(WsMessage::Close(_)) => break, + Ok(WsMessage::Binary(_)) | Ok(WsMessage::Frame(_)) => continue, + Err(e) => { + tracing::debug!("WebSocket read error: {e}"); + break; + } + }; + + let parsed: ClientMessage = match serde_json::from_str(&msg) { + Ok(m) => m, + Err(e) => { + tracing::warn!("invalid WebSocket client message: {e}"); + continue; + } + }; + + match parsed { + ClientMessage::Ping => { + let _ = out_tx.send(ServerMessage::Pong); + } + ClientMessage::Hello { window, project } => { + if let (Some(old_w), Some(old_id)) = (window_label.take(), sub_id.take()) { + state.hub.unsubscribe(&old_w, old_id); + } + let label = sanitize_window_label(window.as_deref()); + let id = state.hub.subscribe(&label, out_tx.clone()); + let requested = project.filter(|p| !p.trim().is_empty()).map(PathBuf::from); + state.shell.seed_launch(&state.host, &label, requested); + window_label = Some(label.clone()); + sub_id = Some(id); + if out_tx + .send(ServerMessage::Ready { + window: label, + instance: state.instance.clone(), + server: rpc::server_info(None), + }) + .is_err() + { + break; + } + } + ClientMessage::Invoke { id, cmd, args } => { + let window = match &window_label { + Some(w) => w.clone(), + None => { + let label = "main".to_owned(); + let sid = state.hub.subscribe(&label, out_tx.clone()); + state.shell.seed_launch(&state.host, &label, None); + window_label = Some(label.clone()); + sub_id = Some(sid); + label + } + }; + let mut arg_channels = Vec::new(); + collect_arg_channels(&args, &mut arg_channels); + let req_id = args.get("request").and_then(|v| serde_json::from_value::(v.clone()).ok()); + if let Some(req) = req_id { + active_requests.lock().insert(req); + } + let state = state.clone(); + let tx = out_tx.clone(); + let active_requests = active_requests.clone(); + tokio::spawn(async move { + let opened_channels: Arc>> = Arc::new(Mutex::new(HashSet::new())); + let ch_tx = tx.clone(); + let opened_for_sink = opened_channels.clone(); + let channel_sink: ChannelSink = Arc::new(move |signal: ChannelSignal| match signal { + ChannelSignal::Opened(cid) => { + opened_for_sink.lock().insert(cid); + } + ChannelSignal::Data(msg) => { + let _ = ch_tx.send(ServerMessage::Channel { id: msg.id, data: msg.data }); + } + ChannelSignal::End(cid) => { + let _ = ch_tx.send(ServerMessage::ChannelEnd { id: cid }); + } + }); + let reply = + match state.dispatcher.invoke(state.host.clone(), window, &cmd, args, channel_sink).await { + Ok(data) => ServerMessage::Response { id, ok: true, data: Some(data), error: None }, + Err(error) => ServerMessage::Response { id, ok: false, data: None, error: Some(error) }, + }; + if let Some(req) = req_id { + active_requests.lock().remove(&req); + } + // Close any channel arguments the command never claimed (e.g. validation or trust error). + if !arg_channels.is_empty() { + let opened = opened_channels.lock(); + for cid in arg_channels { + if !opened.contains(&cid) { + let _ = tx.send(ServerMessage::ChannelEnd { id: cid }); + } + } + } + let _ = tx.send(reply); + }); + } + } + } + + // Cancel any cancellable requests still running for this disconnected session. + let pending_reqs: Vec = active_requests.lock().drain().collect(); + for req in pending_reqs { + state.host.cancel_request(req); + } + + if let (Some(w), Some(id)) = (window_label, sub_id) { + state.hub.unsubscribe(&w, id); + } + drop(out_tx); + let _ = writer.await; +} + +fn sanitize_window_label(raw: Option<&str>) -> String { + let Some(s) = raw else { return "main".into() }; + let clean: String = s.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(64).collect(); + if clean.is_empty() { "main".into() } else { clean } +} + +fn percent_decode(input: &str) -> Option { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + if i + 2 >= bytes.len() { + return None; + } + let hi = hex_val(bytes[i + 1])?; + let lo = hex_val(bytes[i + 2])?; + let byte = (hi << 4) | lo; + if byte == 0 { + return None; + } + out.push(byte); + i += 3; + } else if bytes[i] == b'+' { + out.push(b' '); + i += 1; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).ok() +} + +fn hex_val(b: u8) -> Option { + match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + b'A'..=b'F' => Some(b - b'A' + 10), + _ => None, + } +} + +/// Resolves a static asset inside `web_dir`. +/// +/// First attempts a direct match, then progressively strips leading path segments so that +/// reverse proxies forwarding unstripped prefixes (`rewrite: false`) still resolve `./boot.js`, +/// `./splash.css`, and `./assets/*` cleanly without allowing directory traversal outside `web_dir`. +fn resolve_static_asset(web_dir: &Path, request_path: &str) -> Option<(PathBuf, String)> { + let decoded = percent_decode(request_path)?; + let trimmed = decoded.trim_start_matches('/'); + if trimmed.is_empty() || trimmed.ends_with('/') { + return None; + } + let segments: Vec<&str> = trimmed.split('/').filter(|s| !s.is_empty()).collect(); + if segments.iter().any(|s| *s == "." || *s == ".." || s.contains('\\')) { + return None; + } + for start in 0..segments.len() { + let rel = segments[start..].join("/"); + let mut candidate = web_dir.to_path_buf(); + for seg in &segments[start..] { + candidate.push(seg); + } + // Only accept clean normal components that canonicalize inside `web_dir`. + if candidate.components().any(|c| matches!(c, Component::ParentDir)) { + continue; + } + if let Ok(canon) = dunce::canonicalize(&candidate) + && canon.starts_with(web_dir) + && canon.is_file() + { + return Some((canon, rel)); + } + } + None +} + +fn looks_like_asset_path(path: &str) -> bool { + let last = path.rsplit('/').next().unwrap_or(""); + let Some((_, ext)) = last.rsplit_once('.') else { return false }; + matches!( + ext.to_ascii_lowercase().as_str(), + "js" | "mjs" + | "css" + | "map" + | "svg" + | "png" + | "jpg" + | "jpeg" + | "gif" + | "webp" + | "ico" + | "woff" + | "woff2" + | "ttf" + | "otf" + | "wasm" + | "json" + | "txt" + ) +} + +fn content_type_for(rel: &str) -> &'static str { + let ext = rel.rsplit('.').next().unwrap_or("").to_ascii_lowercase(); + match ext.as_str() { + "html" | "htm" => "text/html; charset=utf-8", + "js" | "mjs" => "application/javascript; charset=utf-8", + "css" => "text/css; charset=utf-8", + "json" | "map" => "application/json; charset=utf-8", + "svg" => "image/svg+xml", + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "gif" => "image/gif", + "webp" => "image/webp", + "ico" => "image/x-icon", + "woff2" => "font/woff2", + "woff" => "font/woff", + "ttf" => "font/ttf", + "otf" => "font/otf", + "wasm" => "application/wasm", + _ => "application/octet-stream", + } +} + +fn accepts_gzip(req: &Request) -> bool { + req.headers().get_all(header::ACCEPT_ENCODING).iter().filter_map(|v| v.to_str().ok()).any(|s| { + s.split(',').any(|part| part.split(';').next().is_some_and(|enc| enc.trim().eq_ignore_ascii_case("gzip"))) + }) +} + +fn is_compressible(rel: &str) -> bool { + let ext = rel.rsplit('.').next().unwrap_or("").to_ascii_lowercase(); + matches!(ext.as_str(), "html" | "htm" | "js" | "mjs" | "css" | "json" | "map" | "svg" | "wasm" | "txt") +} + +fn gzip_bytes(input: &[u8]) -> Option> { + let mut encoder = GzEncoder::new(Vec::with_capacity(input.len() / 3), Compression::fast()); + encoder.write_all(input).ok()?; + let compressed = encoder.finish().ok()?; + (compressed.len() < input.len()).then_some(compressed) +} + +async fn serve_static_file(path: &Path, rel: &str, head_only: bool, gzip: bool) -> Response> { + let cache = if rel.starts_with("assets/") { "public, max-age=31536000, immutable" } else { "no-cache" }; + let compressible = is_compressible(rel); + if head_only { + let Ok(meta) = tokio::fs::metadata(path).await else { + return text_response(StatusCode::NOT_FOUND, "text/plain; charset=utf-8", "Not Found"); + }; + let mut builder = Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, content_type_for(rel)) + .header(header::CONTENT_LENGTH, meta.len().to_string()) + .header(header::CACHE_CONTROL, cache); + if compressible { + builder = builder.header(header::VARY, "Accept-Encoding"); + } + return builder.body(Full::new(Bytes::new())).unwrap(); + } + let bytes = match tokio::fs::read(path).await { + Ok(b) => b, + Err(_) => return text_response(StatusCode::NOT_FOUND, "text/plain; charset=utf-8", "Not Found"), + }; + let (payload, encoded_gzip) = if gzip && compressible && bytes.len() >= GZIP_MIN_BYTES { + match gzip_bytes(&bytes) { + Some(compressed) => (compressed, true), + None => (bytes, false), + } + } else { + (bytes, false) + }; + let len = payload.len(); + let mut builder = Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, content_type_for(rel)) + .header(header::CONTENT_LENGTH, len.to_string()) + .header(header::CACHE_CONTROL, cache); + if compressible { + builder = builder.header(header::VARY, "Accept-Encoding"); + } + if encoded_gzip { + builder = builder.header(header::CONTENT_ENCODING, "gzip"); + } + builder.body(Full::new(Bytes::from(payload))).unwrap() +} + +fn inject_web_meta(html: &str) -> String { + if html.contains(r#"name="openidea-web""#) { + return html.to_owned(); + } + if let Some(pos) = html.find("") { + let mut out = String::with_capacity(html.len() + WEB_META_TAG.len() + 6); + out.push_str(&html[..pos]); + out.push_str(" "); + out.push_str(WEB_META_TAG); + out.push('\n'); + out.push_str(&html[pos..]); + out + } else { + format!("{WEB_META_TAG}\n{html}") + } +} + +async fn serve_index_html(web_dir: &Path, head_only: bool, gzip: bool) -> Response> { + let raw = match tokio::fs::read_to_string(web_dir.join("index.html")).await { + Ok(s) => s, + Err(_) => return text_response(StatusCode::NOT_FOUND, "text/plain; charset=utf-8", "index.html not found"), + }; + let html = inject_web_meta(&raw); + let (payload, encoded_gzip) = if !head_only && gzip && html.len() >= GZIP_MIN_BYTES { + match gzip_bytes(html.as_bytes()) { + Some(compressed) => (Bytes::from(compressed), true), + None => (Bytes::from(html), false), + } + } else { + (Bytes::from(html), false) + }; + let len = payload.len(); + let body = if head_only { Bytes::new() } else { payload }; + let mut builder = Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .header(header::CONTENT_LENGTH, len.to_string()) + .header(header::CACHE_CONTROL, "no-cache") + .header(header::VARY, "Accept-Encoding"); + if encoded_gzip { + builder = builder.header(header::CONTENT_ENCODING, "gzip"); + } + builder.body(Full::new(body)).unwrap() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolves_direct_and_reverse_proxy_prefixed_assets_safely() { + let dir = tempfile::tempdir().unwrap(); + let web_dir = dunce::canonicalize(dir.path()).unwrap(); + std::fs::create_dir_all(web_dir.join("assets")).unwrap(); + std::fs::write(web_dir.join("boot.js"), "console.log('boot');").unwrap(); + std::fs::write(web_dir.join("assets/app.js"), "export {};").unwrap(); + + let (_, rel) = resolve_static_asset(&web_dir, "/boot.js").unwrap(); + assert_eq!(rel, "boot.js"); + + // Unstripped reverse-proxy prefix (rewrite: false). + let (_, rel) = resolve_static_asset(&web_dir, "/user/proj/r/session/abc/assets/app.js").unwrap(); + assert_eq!(rel, "assets/app.js"); + + let (_, rel) = resolve_static_asset(&web_dir, "/proxy/prefix/boot.js").unwrap(); + assert_eq!(rel, "boot.js"); + + // Directory traversal is rejected. + assert!(resolve_static_asset(&web_dir, "/../etc/passwd").is_none()); + assert!(resolve_static_asset(&web_dir, "/prefix/%2e%2e/secret").is_none()); + } + + #[test] + fn injects_web_meta_tag_into_head() { + let html = "OpenIDEA"; + let injected = inject_web_meta(html); + assert!(injected.contains(WEB_META_TAG)); + assert!(injected.find(WEB_META_TAG).unwrap() < injected.find("").unwrap()); + // Idempotent. + assert_eq!(inject_web_meta(&injected), injected); + } + + #[test] + fn strips_configured_base_path() { + assert_eq!(strip_base_path("/ide/api/health", Some("ide")), "/api/health"); + assert_eq!(strip_base_path("/ide", Some("ide")), "/"); + assert_eq!(strip_base_path("/other/path", Some("ide")), "/other/path"); + } + + async fn http_get( + addr: SocketAddr, + path: &str, + extra_headers: &[(&str, &str)], + ) -> (u16, HashMap, String) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + let mut req = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n"); + for (k, v) in extra_headers { + req.push_str(&format!("{k}: {v}\r\n")); + } + req.push_str("\r\n"); + stream.write_all(req.as_bytes()).await.unwrap(); + let mut buf = Vec::new(); + stream.read_to_end(&mut buf).await.unwrap(); + let text = String::from_utf8(buf).unwrap(); + let (head, body) = text.split_once("\r\n\r\n").unwrap(); + let mut lines = head.split("\r\n"); + let status: u16 = lines.next().unwrap().split_whitespace().nth(1).unwrap().parse().unwrap(); + let mut headers = HashMap::new(); + for line in lines { + if let Some((k, v)) = line.split_once(':') { + headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned()); + } + } + (status, headers, body.to_owned()) + } + + #[tokio::test] + async fn end_to_end_http_and_websocket_rpc() { + let tmp = tempfile::tempdir().unwrap(); + let web_dir = tmp.path().join("dist"); + let home_dir = tmp.path().join("home"); + let project_dir = tmp.path().join("sample-project"); + std::fs::create_dir_all(web_dir.join("assets")).unwrap(); + std::fs::create_dir_all(&project_dir).unwrap(); + std::fs::write(web_dir.join("index.html"), "ok").unwrap(); + std::fs::write(web_dir.join("boot.js"), "window.__BOOT=1;").unwrap(); + std::fs::write(project_dir.join("hello.txt"), "hello web ide\n").unwrap(); + + let server = start( + WebServerConfig { + host: "127.0.0.1".into(), + port: 0, + base_path: None, + web_dir, + project: Some(project_dir.clone()), + trust_project: true, + auth_token: None, + }, + home_dir, + ) + .await + .expect("start web server"); + + // 1. Health check works at root and under arbitrary reverse-proxy prefix. + let (status, _, health_txt) = http_get(server.addr, "/api/health", &[]).await; + assert_eq!(status, 200); + let health: Value = serde_json::from_str(&health_txt).unwrap(); + assert_eq!(health["status"], "ok"); + + let (status, _, health2_txt) = http_get(server.addr, "/u/proj/session/42/api/health", &[]).await; + assert_eq!(status, 200); + let health2: Value = serde_json::from_str(&health2_txt).unwrap(); + assert_eq!(health2["status"], "ok"); + + // 2. Entry HTML injects web meta tag; proxy subpath without trailing slash redirects cleanly. + let (status, headers, _) = http_get(server.addr, "/u/proj/session/42", &[]).await; + assert_eq!(status, 307); + assert_eq!(headers.get("location").map(String::as_str), Some("42/")); + + let (status, _, html) = http_get(server.addr, "/u/proj/session/42/", &[]).await; + assert_eq!(status, 200); + assert!(html.contains(WEB_META_TAG)); + + // 3. Static asset works under unstripped reverse-proxy prefix. + let (status, _, js) = http_get(server.addr, "/u/proj/session/42/boot.js", &[]).await; + assert_eq!(status, 200); + assert_eq!(js, "window.__BOOT=1;"); + + // 4. WebSocket RPC works under unstripped reverse-proxy prefix. + let ws_url = format!("ws://{}/u/proj/session/42/api/ws", server.addr); + let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url).await.expect("ws connect"); + ws.send(WsMessage::Text(json!({ "type": "hello", "window": "main" }).to_string().into())).await.unwrap(); + let ready_txt = ws.next().await.unwrap().unwrap().into_text().unwrap(); + let ready: Value = serde_json::from_str(&ready_txt).unwrap(); + assert_eq!(ready["type"], "ready"); + assert_eq!(ready["window"], "main"); + + // `window_take_launch` returns the configured `--project` directory once. + ws.send(WsMessage::Text( + json!({ "type": "invoke", "id": 1, "cmd": "window_take_launch", "args": {} }).to_string().into(), + )) + .await + .unwrap(); + let launch_reply: Value = + serde_json::from_str(&ws.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + assert_eq!(launch_reply["ok"], true); + let launch_project = launch_reply["data"]["project"].as_str().unwrap().to_owned(); + + // `open_project` opens the project and `fs_read_file` reads a file from it. + ws.send(WsMessage::Text( + json!({ "type": "invoke", "id": 2, "cmd": "open_project", "args": { "path": launch_project } }) + .to_string() + .into(), + )) + .await + .unwrap(); + let open_reply = loop { + let msg: Value = serde_json::from_str(&ws.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + if msg["type"] == "response" && msg["id"] == 2 { + break msg; + } + }; + assert_eq!(open_reply["ok"], true); + assert_eq!(open_reply["data"]["trusted"], true); + + let file_path = project_dir.join("hello.txt"); + ws.send(WsMessage::Text( + json!({ "type": "invoke", "id": 3, "cmd": "fs_read_text", "args": { "path": file_path } }) + .to_string() + .into(), + )) + .await + .unwrap(); + let read_reply = loop { + let msg: Value = serde_json::from_str(&ws.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + if msg["type"] == "response" && msg["id"] == 3 { + break msg; + } + }; + assert_eq!(read_reply["ok"], true, "read_reply={read_reply}"); + assert_eq!(read_reply["data"], "hello web ide\n"); + ws.close(None).await.ok(); + + // A reloaded page (a new socket for the same window) gets the project it still has open. + let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url).await.expect("ws reconnect"); + ws.send(WsMessage::Text(json!({ "type": "hello", "window": "main" }).to_string().into())).await.unwrap(); + let ready: Value = serde_json::from_str(&ws.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + assert_eq!(ready["type"], "ready"); + ws.send(WsMessage::Text( + json!({ "type": "invoke", "id": 4, "cmd": "window_take_launch", "args": {} }).to_string().into(), + )) + .await + .unwrap(); + let relaunch = loop { + let msg: Value = serde_json::from_str(&ws.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + if msg["type"] == "response" && msg["id"] == 4 { + break msg; + } + }; + assert_eq!(relaunch["data"]["project"].as_str(), Some(launch_project.as_str())); + + ws.close(None).await.ok(); + server.shutdown().await; + } + + #[tokio::test] + async fn token_authentication_guards_page_and_websocket() { + let tmp = tempfile::tempdir().unwrap(); + let web_dir = tmp.path().join("dist"); + let home_dir = tmp.path().join("home"); + std::fs::create_dir_all(&web_dir).unwrap(); + std::fs::write(web_dir.join("index.html"), "ok").unwrap(); + + let server = start( + WebServerConfig { + host: "127.0.0.1".into(), + port: 0, + base_path: None, + web_dir, + project: None, + trust_project: true, + auth_token: Some("secret-token-123".into()), + }, + home_dir, + ) + .await + .unwrap(); + + // Health stays open for readiness probes. + let (status, _, _) = http_get(server.addr, "/api/health", &[]).await; + assert_eq!(status, 200); + // Unauthenticated entry returns 401 login page. + let (status, _, _) = http_get(server.addr, "/", &[]).await; + assert_eq!(status, 401); + // Valid query token sets cookie and redirects cleanly without token in URL. + let (status, headers, _) = http_get(server.addr, "/?token=secret-token-123", &[]).await; + assert_eq!(status, 302); + assert_eq!(headers.get("location").map(String::as_str), Some("/")); + assert!(headers.get("set-cookie").unwrap().contains("openidea_token=secret-token-123")); + + // Bearer token authorizes entry HTML. + let (status, _, html) = http_get(server.addr, "/", &[("Authorization", "Bearer secret-token-123")]).await; + assert_eq!(status, 200); + assert!(html.contains(WEB_META_TAG)); + + server.shutdown().await; + } + + #[tokio::test] + async fn compresses_large_js_assets_with_gzip() { + use flate2::read::GzDecoder; + use std::io::Read as _; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let tmp = tempfile::tempdir().unwrap(); + let web_dir = tmp.path().join("dist"); + let home_dir = tmp.path().join("home"); + std::fs::create_dir_all(web_dir.join("assets")).unwrap(); + std::fs::write(web_dir.join("index.html"), "ok").unwrap(); + let original = "export const message = 'hello openidea web';\n".repeat(120); + std::fs::write(web_dir.join("assets/bundle.js"), &original).unwrap(); + + let server = start( + WebServerConfig { + host: "127.0.0.1".into(), + port: 0, + base_path: None, + web_dir, + project: None, + trust_project: true, + auth_token: None, + }, + home_dir, + ) + .await + .unwrap(); + + let mut stream = tokio::net::TcpStream::connect(server.addr).await.unwrap(); + let req = format!( + "GET /assets/bundle.js HTTP/1.1\r\nHost: {}\r\nAccept-Encoding: gzip, deflate\r\nConnection: close\r\n\r\n", + server.addr + ); + stream.write_all(req.as_bytes()).await.unwrap(); + let mut buf = Vec::new(); + stream.read_to_end(&mut buf).await.unwrap(); + let sep = buf.windows(4).position(|w| w == b"\r\n\r\n").unwrap(); + let head = std::str::from_utf8(&buf[..sep]).unwrap(); + let body = &buf[sep + 4..]; + assert!(head.contains("content-encoding: gzip"), "head={head}"); + assert!(body.len() < original.len() / 5, "expected strong gzip compression"); + + let mut decoder = GzDecoder::new(body); + let mut decoded = String::new(); + decoder.read_to_string(&mut decoded).unwrap(); + assert_eq!(decoded, original); + + server.shutdown().await; + } + + #[tokio::test] + async fn emits_channel_end_on_streaming_command_completion_and_error() { + let tmp = tempfile::tempdir().unwrap(); + let web_dir = tmp.path().join("dist"); + let home_dir = tmp.path().join("home"); + let proj_dir = tmp.path().join("proj"); + std::fs::create_dir_all(&web_dir).unwrap(); + std::fs::create_dir_all(&proj_dir).unwrap(); + std::fs::write(web_dir.join("index.html"), "ok").unwrap(); + + let server = start( + WebServerConfig { + host: "127.0.0.1".into(), + port: 0, + base_path: None, + web_dir, + project: Some(proj_dir), + trust_project: true, + auth_token: None, + }, + home_dir, + ) + .await + .unwrap(); + + let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{}/api/ws", server.addr)).await.unwrap(); + ws.send(WsMessage::Text(json!({ "type": "hello", "window": "main" }).to_string().into())).await.unwrap(); + let _ready = ws.next().await.unwrap().unwrap(); + + // Command that fails before claiming its channel must still close the channel on the client. + ws.send(WsMessage::Text( + json!({ + "type": "invoke", + "id": 10, + "cmd": "nonexistent_streaming_cmd", + "args": { "onEvent": { "$channel": 77 } } + }) + .to_string() + .into(), + )) + .await + .unwrap(); + + let mut saw_end = false; + let mut saw_reply = false; + while !saw_end || !saw_reply { + let msg: Value = serde_json::from_str(&ws.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + if msg["type"] == "channelEnd" && msg["id"] == 77 { + saw_end = true; + } else if msg["type"] == "response" && msg["id"] == 10 { + saw_reply = true; + } + } + assert!(saw_end && saw_reply); + + ws.close(None).await.ok(); + server.shutdown().await; + } + + #[tokio::test] + async fn validates_same_origin_and_rejects_cross_origin_websocket() { + assert!(is_same_origin(None, Some("localhost:8080"), None)); + assert!(is_same_origin(Some("http://localhost:8080"), Some("localhost:8080"), None)); + assert!(is_same_origin(Some("https://ide.example.com"), Some("ide.example.com:443"), None)); + assert!(is_same_origin(Some("https://proxy.example.com"), Some("127.0.0.1:8080"), Some("proxy.example.com"))); + assert!(!is_same_origin(Some("https://evil.example"), Some("localhost:8080"), None)); + assert!(!is_same_origin(Some("null"), Some("localhost:8080"), None)); + + let tmp = tempfile::tempdir().unwrap(); + let web_dir = tmp.path().join("dist"); + let home_dir = tmp.path().join("home"); + std::fs::create_dir_all(&web_dir).unwrap(); + std::fs::write(web_dir.join("index.html"), "ok").unwrap(); + + let server = start( + WebServerConfig { + host: "127.0.0.1".into(), + port: 0, + base_path: None, + web_dir, + project: None, + trust_project: true, + auth_token: None, + }, + home_dir, + ) + .await + .unwrap(); + + let (status, _, _) = http_get( + server.addr, + "/api/ws", + &[ + ("Connection", "Upgrade"), + ("Upgrade", "websocket"), + ("Sec-WebSocket-Version", "13"), + ("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="), + ("Origin", "https://evil.example"), + ], + ) + .await; + assert_eq!(status, 403); + + server.shutdown().await; + } + + #[tokio::test] + async fn supersedes_previous_tab_on_same_window_without_affecting_other_windows() { + let tmp = tempfile::tempdir().unwrap(); + let web_dir = tmp.path().join("dist"); + let home_dir = tmp.path().join("home"); + std::fs::create_dir_all(&web_dir).unwrap(); + std::fs::write(web_dir.join("index.html"), "ok").unwrap(); + + let server = start( + WebServerConfig { + host: "127.0.0.1".into(), + port: 0, + base_path: None, + web_dir, + project: None, + trust_project: true, + auth_token: None, + }, + home_dir, + ) + .await + .unwrap(); + + let url = format!("ws://{}/api/ws", server.addr); + let (mut ws1, _) = tokio_tungstenite::connect_async(&url).await.unwrap(); + ws1.send(WsMessage::Text(json!({ "type": "hello", "window": "main" }).to_string().into())).await.unwrap(); + let ready1: Value = serde_json::from_str(&ws1.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + assert_eq!(ready1["type"], "ready"); + + // Opening a different window label on the same server does not displace "main". + let (mut ws_other, _) = tokio_tungstenite::connect_async(&url).await.unwrap(); + ws_other.send(WsMessage::Text(json!({ "type": "hello", "window": "web-2" }).to_string().into())).await.unwrap(); + let ready_other: Value = + serde_json::from_str(&ws_other.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + assert_eq!(ready_other["type"], "ready"); + + // Opening a second tab on the SAME window ("main") displaces ws1 with "superseded". + let (mut ws2, _) = tokio_tungstenite::connect_async(&url).await.unwrap(); + ws2.send(WsMessage::Text(json!({ "type": "hello", "window": "main" }).to_string().into())).await.unwrap(); + let ready2: Value = serde_json::from_str(&ws2.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + assert_eq!(ready2["type"], "ready"); + + let displaced: Value = serde_json::from_str(&ws1.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + assert_eq!(displaced["type"], "superseded"); + + // ws_other ("web-2") still answers pings normally. + ws_other.send(WsMessage::Text(json!({ "type": "ping" }).to_string().into())).await.unwrap(); + let pong: Value = serde_json::from_str(&ws_other.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); + assert_eq!(pong["type"], "pong"); + + ws2.close(None).await.ok(); + ws_other.close(None).await.ok(); + server.shutdown().await; + } + + #[tokio::test] + async fn scopes_auth_cookie_path_and_sets_secure_behind_https_proxy() { + assert_eq!(cookie_scope_path("/"), "/"); + assert_eq!(cookie_scope_path("/user/proj/r/session/1/"), "/user/proj/r/session/1/"); + assert_eq!(cookie_scope_path("/user/proj/r/session/1/api/auth"), "/user/proj/r/session/1/"); + + let tmp = tempfile::tempdir().unwrap(); + let web_dir = tmp.path().join("dist"); + let home_dir = tmp.path().join("home"); + std::fs::create_dir_all(&web_dir).unwrap(); + std::fs::write(web_dir.join("index.html"), "ok").unwrap(); + + let server = start( + WebServerConfig { + host: "127.0.0.1".into(), + port: 0, + base_path: None, + web_dir, + project: None, + trust_project: true, + auth_token: Some("tok-abc".into()), + }, + home_dir, + ) + .await + .unwrap(); + + let (status, headers, _) = + http_get(server.addr, "/user/proj/r/session/42/?token=tok-abc", &[("X-Forwarded-Proto", "https")]).await; + assert_eq!(status, 302); + let cookie = headers.get("set-cookie").unwrap(); + assert!(cookie.contains("Path=/user/proj/r/session/42/"), "cookie={cookie}"); + assert!(cookie.contains("; Secure"), "cookie={cookie}"); + assert!(cookie.contains("HttpOnly"), "cookie={cookie}"); + + server.shutdown().await; + } +} diff --git a/docs/docs.json b/docs/docs.json index 5d14086a37..acb17d7e30 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -96,7 +96,12 @@ }, { "group": "Remote development", - "pages": ["en/guide/remote/ssh", "en/guide/remote/server", "en/guide/remote/containers"] + "pages": [ + "en/guide/remote/ssh", + "en/guide/remote/server", + "en/guide/remote/containers", + "en/guide/web-server" + ] }, { "group": "Customize", @@ -320,7 +325,12 @@ }, { "group": "远程开发", - "pages": ["zh/guide/remote/ssh", "zh/guide/remote/server", "zh/guide/remote/containers"] + "pages": [ + "zh/guide/remote/ssh", + "zh/guide/remote/server", + "zh/guide/remote/containers", + "zh/guide/web-server" + ] }, { "group": "定制", diff --git a/docs/en/guide/web-server.mdx b/docs/en/guide/web-server.mdx new file mode 100644 index 0000000000..c139303c91 --- /dev/null +++ b/docs/en/guide/web-server.mdx @@ -0,0 +1,83 @@ +--- +title: Web Server Mode +description: Run OpenIDEA in a web browser on a configurable host and port, directly or behind a reverse proxy. +--- + +OpenIDEA can run as a headless web application using `openidea-server --web`. The server hosts the built frontend assets and exposes the full Rust IDE backend (files, search, LSP code intelligence, integrated terminal, Git, run/debug, settings) over a single HTTP + WebSocket port. + +## Build + +Build both the frontend bundle and `openidea-server`: + +```bash +pnpm install +pnpm build +cargo build --release -p ide-host --bin openidea-server +``` + +## Run + +The quickest way to launch the web IDE (from a repo checkout or inside a container) is the standalone launcher script: + +```bash +./scripts/start-web.sh +``` + +It listens on `127.0.0.1:8080` by default (set `OPENIDEA_HOST=0.0.0.0` inside a container; `OPENIDEA_PORT` changes the port), auto-detects the `openidea-server` binary, the built `dist/` folder, and the workspace directory, and stores persistent settings and caches in `~/.openidea` (outside the workspace so indexes and downloaded tools are not watched as project files). + +Or invoke `openidea-server --web` directly on any host and port (default: `127.0.0.1:8080`): + +```bash +./target/release/openidea-server --web \ + --host 0.0.0.0 \ + --port 8080 \ + --web-dir ./dist \ + --project /path/to/workspace +``` + +Then open `http://localhost:8080/` in a browser. + +## CLI Options & Environment Variables + +| Flag | Environment Variable | Default | Description | +| ------------------------ | ------------------------ | -------------------------- | --------------------------------------------------------------------------- | +| `--host ` | `OPENIDEA_HOST` | `127.0.0.1` | Bind address (use `0.0.0.0` inside containers) | +| `--port ` | `OPENIDEA_PORT` | `8080` | TCP port for HTTP and WebSocket traffic | +| `--base-path ` | `OPENIDEA_BASE_PATH` | _(auto)_ | Optional reverse-proxy URL prefix | +| `--web-dir ` | `OPENIDEA_WEB_DIR` | auto-detected `dist/` | Built frontend directory | +| `--project ` | `OPENIDEA_WORKSPACE_DIR` | _(none)_ | Workspace folder opened automatically on startup | +| `--home ` | `OPENIDEA_SERVER_HOME` | `~/.openidea` | Persistent directory for settings, indexes, and caches | +| `--token ` | `OPENIDEA_WEB_TOKEN` | `auto` (random token) | Access token required for browser and WebSocket sessions | +| `--no-auth` | `OPENIDEA_WEB_NO_AUTH` | _(disabled)_ | Disable built-in token auth (use only behind an authenticating proxy) | +| `--no-trust-project` | — | _(auto-trust `--project`)_ | Prompt for trust confirmation instead of trusting `--project` automatically | + +## Reverse Proxy & Subpath Deployments + +OpenIDEA web mode uses relative asset URLs and relative WebSocket resolution (`api/ws`), and automatically resolves static assets and API endpoints whether a reverse proxy strips its path prefix or forwards the full prefix untouched: + +- **Direct access**: `http://localhost:8080/` +- **Prefix-stripping proxy**: `https://proxy.example/ide/` → backend receives `/` and `/api/ws` +- **Prefix-preserving proxy**: `https://proxy.example/user/session/123/` → backend receives `/user/session/123/` and `/user/session/123/api/ws` + +### Health Endpoint + +`GET /api/health` (also reachable under any proxy prefix, e.g. `.../api/health`) returns `200 OK` with JSON status without requiring authentication, suitable for container readiness and liveness probes. + +## Authentication & Security + +Web mode is **authenticated by default**: + +- `openidea-server --web` binds to `127.0.0.1` by default and generates a random access token unless `--token ` or `--no-auth` is passed. +- On startup, the server prints a one-click URL containing `?token=...` (which sets a path-scoped `HttpOnly; SameSite=Lax` cookie — plus `Secure` behind HTTPS proxies — and redirects to strip the token from the URL) and serves a sign-in form for unauthenticated visitors. +- WebSocket upgrades (`/api/ws`) enforce same-origin validation (`Origin` against `Host` / `X-Forwarded-Host`) to block Cross-Site WebSocket Hijacking (CSWSH). +- When running behind a reverse proxy that already authenticates every request, disable built-in token auth explicitly with `--no-auth` or `OPENIDEA_WEB_NO_AUTH=1`. Never expose the server without authentication: anyone who reaches it can read and write files and run commands. + +## Session Lifecycle & Browser Tabs + +- **Server-owned state**: Open projects, terminals, background runs, and language servers live in `openidea-server`, not in the browser tab. Reloading or briefly disconnecting preserves running processes and reconnects automatically. When the server itself restarted, the tab reloads, since what it showed is gone. +- **Unsaved-changes protection**: The browser prompts before closing or reloading a tab when open buffers have unsaved edits. +- **Single active tab per window**: Opening the same server window in a second tab hands control to the newer tab and pauses the older tab with a **Take Over** banner to avoid conflicting edits. Independent server instances (for example two separate workspace containers under the same proxy domain) have isolated server hubs and path-scoped cookies, so they run side by side without interfering. + +## Persistent Storage & Containers + +In ephemeral container environments, point `OPENIDEA_SERVER_HOME` at a mounted persistent volume outside the project directory (for example `/home/openidea/.openidea`) so settings, recent projects, and indexes survive restarts without being watched or indexed as project files. diff --git a/docs/zh/guide/web-server.mdx b/docs/zh/guide/web-server.mdx new file mode 100644 index 0000000000..b4ff7cbdc9 --- /dev/null +++ b/docs/zh/guide/web-server.mdx @@ -0,0 +1,83 @@ +--- +title: Web 服务器模式 +description: 在浏览器中使用 OpenIDEA:服务器监听可配置的地址和端口,可以直接访问,也可以放在反向代理后面。 +--- + +`openidea-server --web` 让 OpenIDEA 以不带桌面窗口的 Web 应用运行。服务器托管构建好的前端,并通过同一个 HTTP + WebSocket 端口提供完整的 IDE 后端:文件、搜索、语言服务器的代码智能、终端、Git、运行和调试、设置。 + +## 构建 + +先构建前端和 `openidea-server`: + +```bash +pnpm install +pnpm build +cargo build --release -p ide-host --bin openidea-server +``` + +## 运行 + +在仓库目录或容器中,最简单的方式是启动脚本: + +```bash +./scripts/start-web.sh +``` + +它默认监听 `127.0.0.1:8080`(在容器中设置 `OPENIDEA_HOST=0.0.0.0`,端口用 `OPENIDEA_PORT` 修改),自动找到 `openidea-server`、构建好的 `dist/` 和工作区目录,并把设置和缓存放在 `~/.openidea`(放在工作区之外,索引和下载的工具不会被当作项目文件监视)。 + +也可以直接运行 `openidea-server --web`(默认 `127.0.0.1:8080`): + +```bash +./target/release/openidea-server --web \ + --host 0.0.0.0 \ + --port 8080 \ + --web-dir ./dist \ + --project /path/to/workspace +``` + +然后在浏览器中打开 `http://localhost:8080/`。 + +## 命令行选项和环境变量 + +| 选项 | 环境变量 | 默认值 | 说明 | +| ------------------------ | ------------------------ | -------------------------- | ----------------------------------------------- | +| `--host ` | `OPENIDEA_HOST` | `127.0.0.1` | 监听地址(容器中用 `0.0.0.0`) | +| `--port ` | `OPENIDEA_PORT` | `8080` | HTTP 和 WebSocket 共用的端口 | +| `--base-path ` | `OPENIDEA_BASE_PATH` | _(自动)_ | 反向代理的 URL 前缀 | +| `--web-dir ` | `OPENIDEA_WEB_DIR` | 自动查找 `dist/` | 构建好的前端目录 | +| `--project ` | `OPENIDEA_WORKSPACE_DIR` | _(无)_ | 启动时自动打开的工作区 | +| `--home ` | `OPENIDEA_SERVER_HOME` | `~/.openidea` | 保存设置、索引和缓存的目录 | +| `--token ` | `OPENIDEA_WEB_TOKEN` | `auto`(随机令牌) | 浏览器和 WebSocket 会话需要的访问令牌 | +| `--no-auth` | `OPENIDEA_WEB_NO_AUTH` | _(关闭)_ | 关闭内置令牌认证(仅用于已做认证的反向代理后) | +| `--no-trust-project` | — | _(自动信任 `--project`)_ | 打开 `--project` 时询问是否信任,而不是自动信任 | + +## 反向代理和子路径 + +Web 模式使用相对的资源地址,WebSocket 地址(`api/ws`)也按当前页面解析。无论反向代理去掉还是保留路径前缀,静态资源和接口都能找到: + +- **直接访问**:`http://localhost:8080/` +- **去掉前缀的代理**:`https://proxy.example/ide/` → 后端收到 `/` 和 `/api/ws` +- **保留前缀的代理**:`https://proxy.example/user/session/123/` → 后端收到 `/user/session/123/` 和 `/user/session/123/api/ws` + +### 健康检查 + +`GET /api/health`(在任何代理前缀下也可以访问,例如 `.../api/health`)返回 `200 OK` 和 JSON 状态,不需要认证,可用于容器的就绪和存活探针。 + +## 认证和安全 + +Web 模式**默认需要认证**: + +- `openidea-server --web` 默认只监听 `127.0.0.1`,除非传入 `--token ` 或 `--no-auth`,否则生成一个随机访问令牌。 +- 启动时服务器打印一个带 `?token=...` 的链接。打开它会设置一个限定路径的 `HttpOnly; SameSite=Lax` Cookie(在 HTTPS 代理后还带 `Secure`),并跳转到不含令牌的地址。未认证的访问者看到登录页。 +- WebSocket 升级(`/api/ws`)校验 `Origin` 与 `Host` / `X-Forwarded-Host` 同源,防止跨站 WebSocket 劫持。 +- 如果反向代理已经认证每个请求,用 `--no-auth` 或 `OPENIDEA_WEB_NO_AUTH=1` 关闭内置认证。不要在没有认证的情况下暴露服务器:任何能访问它的人都能读写文件、运行命令。 + +## 会话和浏览器标签页 + +- **状态在服务器上**:打开的项目、终端、后台运行和语言服务器都在 `openidea-server` 中,而不在标签页里。刷新页面或短暂断线不会中断正在运行的进程,连接会自动恢复。如果服务器本身重启了,标签页会重新加载,因为之前显示的内容已经不存在。 +- **未保存的修改**:编辑器中有未保存的修改时,关闭或刷新标签页前浏览器会提示。 +- **每个窗口只有一个活动标签页**:在第二个标签页打开同一个服务器窗口时,新标签页接管,旧标签页暂停并显示**接管会话**按钮,避免两边同时编辑。相互独立的服务器实例(例如同一代理域名下的两个工作区容器)各自独立,Cookie 也限定在各自路径下,可以同时使用。 + +## 持久化存储和容器 + +在临时容器中,把 `OPENIDEA_SERVER_HOME` 指向挂载的持久卷,并放在项目目录之外(例如 `/home/openidea/.openidea`),这样设置、最近项目和索引在重启后保留,也不会被当作项目文件监视或索引。 diff --git a/index.html b/index.html index 845b697dad..088c4f77cb 100644 --- a/index.html +++ b/index.html @@ -4,8 +4,8 @@ OpenIDEA - - + +
diff --git a/scripts/start-web.sh b/scripts/start-web.sh new file mode 100755 index 0000000000..607fee5d02 --- /dev/null +++ b/scripts/start-web.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Standalone launcher for running OpenIDEA in browser web server mode. +# Designed to work directly from a repository checkout or inside a container / +# remote workspace environment with zero required arguments. +# +# Environment variables (all optional): +# OPENIDEA_HOST Bind address (default: 127.0.0.1; 0.0.0.0 in a container) +# OPENIDEA_PORT Listen port (default: 8080) +# OPENIDEA_WORKSPACE_DIR Workspace folder to open on startup (default: the +# first argument if it is a folder, else /workspace if +# it exists, else the current directory) +# OPENIDEA_SERVER_HOME Persistent config/data directory (defaults to +# ~/.openidea, outside the workspace so caches and +# tools are never indexed or watched as project files) +# OPENIDEA_WEB_DIR Built frontend directory (default: /dist) +# OPENIDEA_SERVER_BIN Path to openidea-server binary (auto-detected) +# OPENIDEA_BASE_PATH Optional reverse-proxy URL prefix +# OPENIDEA_WEB_TOKEN Access token (default: auto-generated by openidea-server) +# OPENIDEA_WEB_NO_AUTH Set to 1 to disable token auth behind an authenticating proxy + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd)" + +HOST="${OPENIDEA_HOST:-127.0.0.1}" +PORT="${OPENIDEA_PORT:-8080}" + +# Limit glibc malloc arenas so bursty thread pools do not retain excess RSS in containers. +export MALLOC_ARENA_MAX="${MALLOC_ARENA_MAX:-2}" + +# 1. Resolve workspace directory. +WORKSPACE_DIR="${OPENIDEA_WORKSPACE_DIR:-${WORKSPACE_DIR:-}}" +if [[ -z "${WORKSPACE_DIR}" && $# -gt 0 && "${1}" != -* && -d "${1}" ]]; then + WORKSPACE_DIR="${1}" + shift +fi +if [[ -z "${WORKSPACE_DIR}" ]]; then + if [[ -d "/workspace" ]]; then + WORKSPACE_DIR="/workspace" + else + WORKSPACE_DIR="${PWD}" + fi +fi + +# 2. Resolve persistent config/data directory (keep outside WORKSPACE_DIR). +if [[ -z "${OPENIDEA_SERVER_HOME:-}" ]]; then + export OPENIDEA_SERVER_HOME="${HOME:-/tmp}/.openidea" +fi +mkdir -p "${OPENIDEA_SERVER_HOME}/config" "${OPENIDEA_SERVER_HOME}/data" + +# 3. Resolve openidea-server binary. +BIN="${OPENIDEA_SERVER_BIN:-}" +if [[ -z "${BIN}" ]]; then + if command -v openidea-server >/dev/null 2>&1; then + BIN="$(command -v openidea-server)" + elif [[ -x "${REPO_ROOT}/target/release/openidea-server" ]]; then + BIN="${REPO_ROOT}/target/release/openidea-server" + elif [[ -x "${REPO_ROOT}/target/debug/openidea-server" ]]; then + BIN="${REPO_ROOT}/target/debug/openidea-server" + else + echo "error: openidea-server binary not found. Build it with:" >&2 + echo " cargo build --release -p ide-host --bin openidea-server" >&2 + exit 1 + fi +fi + +# 4. Resolve built frontend assets directory. +WEB_DIR="${OPENIDEA_WEB_DIR:-}" +if [[ -z "${WEB_DIR}" ]]; then + for candidate in "${REPO_ROOT}/dist" "${PWD}/dist"; do + if [[ -f "${candidate}/index.html" ]]; then + WEB_DIR="${candidate}" + break + fi + done +fi +if [[ -z "${WEB_DIR}" || ! -f "${WEB_DIR}/index.html" ]]; then + echo "error: built frontend (index.html) not found. Build it with:" >&2 + echo " pnpm build" >&2 + exit 1 +fi + +ARGS=( + --web + --host "${HOST}" + --port "${PORT}" + --web-dir "${WEB_DIR}" + --home "${OPENIDEA_SERVER_HOME}" +) + +if [[ -n "${WORKSPACE_DIR}" ]]; then + ARGS+=(--project "${WORKSPACE_DIR}") +fi + +if [[ -n "${OPENIDEA_BASE_PATH:-}" ]]; then + ARGS+=(--base-path "${OPENIDEA_BASE_PATH}") +fi + +if [[ -n "${OPENIDEA_WEB_TOKEN:-}" ]]; then + ARGS+=(--token "${OPENIDEA_WEB_TOKEN}") +elif [[ "${OPENIDEA_WEB_NO_AUTH:-}" == "1" || "${OPENIDEA_WEB_NO_AUTH:-}" == "true" ]]; then + ARGS+=(--no-auth) +fi + +echo "Starting OpenIDEA Web Server on ${HOST}:${PORT} (workspace: ${WORKSPACE_DIR}, home: ${OPENIDEA_SERVER_HOME})" >&2 +exec "${BIN}" "${ARGS[@]}" "$@" diff --git a/src-tauri/src/commands/app.rs b/src-tauri/src/commands/app.rs index 154ff13783..42a4b6cf5c 100644 --- a/src-tauri/src/commands/app.rs +++ b/src-tauri/src/commands/app.rs @@ -171,16 +171,7 @@ fn project_info(project: &crate::state::Project) -> ProjectInfo { #[tauri::command] #[specta::specta] pub fn project_rename(window: Window, state: State<'_, AppState>, name: String) -> IdeResult { - let project = state.project(window.label())?; - let name = name.trim(); - if let Some(workspace) = ide_workspace::workspace::Workspace::load(&project.root)? - && workspace.is_container(&project.root) - { - ide_host::ops::project::save_workspace(&state.host, window.label(), name, workspace.projects)?; - } else { - let value = if name.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(name.to_owned()) }; - project.settings.set(SettingsScope::Project, "general.projectName", value)?; - } + let project = ide_host::ops::project::rename(&state.host, window.label(), &name)?; let info = project_info(&project); state.record_project(&project)?; let _ = window.set_title(&info.display_name); diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 47f4f355ce..53b22769e1 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -258,4 +258,23 @@ mod tests { served.sort_unstable(); assert_eq!(super::routed(), served); } + + /// `openidea-server --web` serves the desktop's shell commands itself: each must be one the + /// desktop declares, with the same trust class, so a browser window is gated like a desktop one. + #[test] + fn web_shell_commands_match_the_desktop_declarations() { + let home = tempfile::tempdir().unwrap(); + let standard = ide_host::rpc::Dispatcher::standard(); + let mut web = ide_host::rpc::Dispatcher::standard(); + let shell = ide_host::web_server::commands::WebShellState::new(home.path(), None, false); + ide_host::web_server::commands::register(&mut web, std::sync::Arc::new(shell)); + let mismatched: Vec<_> = web + .commands() + .into_iter() + .filter(|name| standard.trust(name).is_none()) + .filter(|name| super::trust_of(name) != web.trust(name)) + .map(|name| (name, web.trust(name), super::trust_of(name))) + .collect(); + assert!(mismatched.is_empty(), "(command, web, desktop): {mismatched:?}"); + } } diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 9fc414d22f..dc41117f22 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -17,908 +17,15 @@ //! a spec accelerator fire natively for keys the keymap never binds: Quit and //! window cycling, next to the macOS clipboard/undo roles that text inputs need. +pub use ide_host::menu::*; use parking_lot::Mutex; -use serde::{Deserialize, Serialize}; -use specta::Type; -use std::collections::{HashMap, HashSet}; -use std::path::Path; +use serde::Serialize; +use std::collections::HashSet; use tauri::menu::{CheckMenuItem, IsMenuItem, Menu, MenuItem, MenuItemKind, NativeIcon, PredefinedMenuItem, Submenu}; use tauri::{AppHandle, Runtime}; /// Event emitted to the focused window when an IDE menu item is clicked. pub const MENU_EVENT: &str = "openidea://menu"; -/// Prefix of Open Recent item ids; the rest of the id is the project path. -const RECENT_PREFIX: &str = "recent:"; -/// Prefix of items the frontend lists ([`MenuConfig::dynamic`]): `dyn:` or `dyn:|`. -const DYNAMIC_PREFIX: &str = "dyn:"; -/// Action run for an Open Recent entry (argument: the project path). -pub const OPEN_RECENT_ACTION: &str = "file.openRecentProject"; -const MAX_RECENT: usize = 15; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Os { - Mac, - Windows, - Linux, -} - -impl Os { - pub fn current() -> Self { - if cfg!(target_os = "macos") { - Os::Mac - } else if cfg!(target_os = "windows") { - Os::Windows - } else { - Os::Linux - } - } -} - -/// Native (role) items, implemented by the OS. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Native { - Undo, - Redo, - Cut, - Copy, - Paste, - SelectAll, - Services, - Hide, - HideOthers, - ShowAll, - Minimize, - Zoom, - BringAllToFront, -} - -impl Native { - fn key(self) -> &'static str { - match self { - Native::Undo => "native.undo", - Native::Redo => "native.redo", - Native::Cut => "native.cut", - Native::Copy => "native.copy", - Native::Paste => "native.paste", - Native::SelectAll => "native.selectAll", - Native::Services => "native.services", - Native::Hide => "native.hide", - Native::HideOthers => "native.hideOthers", - Native::ShowAll => "native.showAll", - Native::Minimize => "native.minimize", - Native::Zoom => "native.zoom", - Native::BringAllToFront => "native.bringAllToFront", - } - } - - fn default_label(self) -> &'static str { - match self { - Native::Undo => "Undo", - Native::Redo => "Redo", - Native::Cut => "Cut", - Native::Copy => "Copy", - Native::Paste => "Paste", - Native::SelectAll => "Select All", - Native::Services => "Services", - Native::Hide => "Hide OpenIDEA", - Native::HideOthers => "Hide Others", - Native::ShowAll => "Show All", - Native::Minimize => "Minimize", - Native::Zoom => "Zoom", - Native::BringAllToFront => "Bring All to Front", - } - } - - /// Accelerator the OS attaches implicitly (macOS), in keymap syntax. - #[cfg(test)] - fn implicit_accelerator(self) -> Option<&'static str> { - match self { - Native::Undo => Some("Meta+Z"), - Native::Redo => Some("Meta+Shift+Z"), - Native::Cut => Some("Meta+X"), - Native::Copy => Some("Meta+C"), - Native::Paste => Some("Meta+V"), - Native::SelectAll => Some("Meta+A"), - Native::Hide => Some("Meta+H"), - Native::HideOthers => Some("Meta+Alt+H"), - Native::Minimize => Some("Meta+M"), - _ => None, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Entry { - Submenu { - id: &'static str, - label: &'static str, - children: Vec, - }, - /// An IDE action; `id` is the action id. - Action { - id: &'static str, - label: &'static str, - /// Native accelerator (Tauri syntax) that fires natively ([`fires_natively`]) and wins - /// over the keymap's. Only for keys the webview never handles. - accel: Option<&'static str>, - /// Shortcut text after the label, for the Windows/Linux edit items without a keymap binding. - hint: Option<&'static str>, - /// A toggle (IDEA's ToggleAction) drawn with a check mark; on when its id is in - /// [`MenuConfig::checked`]. - check: bool, - }, - Native(Native), - Separator, - /// Open Recent entries, filled from the recent-projects list. - RecentProjects, - /// Items the frontend lists under this slot name (registered tool windows, - /// saved layouts), from [`MenuConfig::dynamic`]. - Dynamic(&'static str), -} - -fn sub(id: &'static str, label: &'static str, children: Vec) -> Entry { - Entry::Submenu { id, label, children } -} -fn act(id: &'static str, label: &'static str) -> Entry { - Entry::Action { id, label, accel: None, hint: None, check: false } -} -fn accel(id: &'static str, label: &'static str, accel: &'static str) -> Entry { - Entry::Action { id, label, accel: Some(accel), hint: None, check: false } -} -fn hinted(id: &'static str, label: &'static str, hint: &'static str) -> Entry { - Entry::Action { id, label, accel: None, hint: Some(hint), check: false } -} -fn toggle(id: &'static str, label: &'static str) -> Entry { - Entry::Action { id, label, accel: None, hint: None, check: true } -} -const SEP: Entry = Entry::Separator; - -/// [`Entry::Dynamic`] slots the frontend fills. -pub const DYNAMIC_TOOL_WINDOWS: &str = "toolWindows"; -pub const DYNAMIC_LAYOUTS: &str = "toolWindowLayouts"; -/// View › Appearance › Status Bar Widgets: every titled widget with its check mark. -pub const DYNAMIC_STATUS_BAR_WIDGETS: &str = "statusBarWidgets"; -/// Tools › entries of plugins (`[[contributes.menus]] menu = "tools"`). -pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools"; -/// Build › Flutter: the Flutter build actions, filled only in Flutter projects. Shown as a submenu -/// first in Build (the Flutter plugin's anchor) when it has items, nothing otherwise. -pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild"; -/// Id (and `menu.` label key) of the Build › Flutter submenu. -const FLUTTER_BUILD_MENU: &str = "build.flutter"; - -/// The menu bar for `os`. Labels are English defaults; the frontend replaces -/// them with `menu.` strings from the active locale catalog. -pub fn spec(os: Os) -> Vec { - let mac = os == Os::Mac; - let show_log = match os { - Os::Mac => "Show Log in Finder", - Os::Windows => "Show Log in Explorer", - Os::Linux => "Show Log in Files", - }; - let mut menus = Vec::new(); - - if mac { - menus.push(sub( - "app", - "OpenIDEA", - vec![ - act("app.about", "About OpenIDEA"), - act("app.checkForUpdates", "Check for Updates…"), - SEP, - act("app.installCli", "Install 'openidea' Command"), - act("app.uninstallCli", "Uninstall 'openidea' Command"), - SEP, - act("file.settings", "Settings…"), - SEP, - Entry::Native(Native::Services), - SEP, - Entry::Native(Native::Hide), - Entry::Native(Native::HideOthers), - Entry::Native(Native::ShowAll), - SEP, - accel("app.quit", "Quit OpenIDEA", "CmdOrCtrl+Q"), - ], - )); - } - - let mut file = vec![ - sub( - "new", - "New", - vec![ - act("file.newProject", "Project…"), - act("workspace.create", "Workspace…"), - act("vcs.cloneProject", "Project from Version Control…"), - SEP, - act("file.new", "File…"), - act("file.newScratchFile", "Scratch File"), - act("file.newUntitled", "Untitled File"), - ], - ), - act("file.openProject", "Open…"), - act("file.openFile", "Open File…"), - act("file.openInNewWindow", "Open in New Window…"), - sub( - "openRecent", - "Open Recent", - vec![Entry::RecentProjects, SEP, act("welcome.recentProjects", "Manage Projects…")], - ), - act("project.attach", "Attach Project…"), - SEP, - act("workspace.open", "Open Workspace…"), - act("workspace.manage", "Manage Workspace…"), - SEP, - act("file.closeProject", "Close Project"), - act("file.renameProject", "Rename Project…"), - SEP, - act("remote.connect", "Remote Development…"), - act("remote.reopenInContainer", "Reopen in Container"), - act("remote.disconnect", "Disconnect from Remote Host"), - act("remote.stopBackend", "Stop Remote Backend"), - act("remote.reloadEnvironment", "Reload Environment"), - SEP, - act("file.save", "Save All"), - act("file.reloadAllFromDisk", "Reload All from Disk"), - sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]), - SEP, - act("file.projectStructure", "Project Structure…"), - SEP, - act("file.invalidateCaches", "Invalidate Caches…"), - SEP, - sub( - "manageIdeSettings", - "Manage IDE Settings", - vec![ - act("file.exportSettings", "Export Settings…"), - act("file.importSettings", "Import Settings…"), - act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"), - ], - ), - sub( - "newProjectsSetup", - "New Projects Setup", - vec![act("file.newProjectsSettings", "Settings for New Projects…")], - ), - SEP, - act("file.togglePowerSave", "Power Save Mode"), - ]; - if !mac { - // macOS keeps Settings… and Quit in the application menu. - file.extend([SEP, act("file.settings", "Settings…"), SEP, accel("app.quit", "Exit", "Ctrl+Q")]); - } - menus.push(sub("file", "File", file)); - - let find = sub( - "find", - "Find", - vec![ - act("find.inFile", "Find…"), - act("find.replaceInFile", "Replace…"), - SEP, - act("find.inPath", "Find in Files…"), - act("find.replaceInPath", "Replace in Files…"), - act("find.structural", "Search Structurally…"), - act("find.replaceStructural", "Replace Structurally…"), - SEP, - act("find.usages", "Find Usages"), - act("find.showUsages", "Show Usages"), - ], - ); - let macros = || { - sub( - "macros", - "Macros", - vec![ - act("macro.startRecording", "Start Macro Recording"), - act("macro.stopRecording", "Stop Macro Recording"), - act("macro.playBack", "Play Back Last Macro"), - SEP, - act("macro.playSaved", "Play Saved Macros…"), - act("macro.edit", "Edit Macros…"), - ], - ) - }; - let bookmarks = || { - sub( - "bookmarks", - "Bookmarks", - vec![ - act("navigate.toggleBookmark", "Toggle Bookmark"), - act("navigate.toggleBookmarkWithMnemonic", "Toggle Bookmark with Mnemonic"), - SEP, - act("navigate.showBookmarks", "Show All Bookmarks…"), - act("navigate.nextBookmark", "Next Bookmark"), - act("navigate.prevBookmark", "Previous Bookmark"), - ], - ) - }; - let edit = if mac { - vec![ - Entry::Native(Native::Undo), - Entry::Native(Native::Redo), - SEP, - Entry::Native(Native::Cut), - Entry::Native(Native::Copy), - Entry::Native(Native::Paste), - act("code.pasteFromHistory", "Paste from History…"), - act("code.pasteAsPlainText", "Paste as Plain Text"), - Entry::Native(Native::SelectAll), - SEP, - find, - SEP, - act("editor.copyPath", "Copy Path"), - act("editor.copyReference", "Copy Reference"), - SEP, - act("code.sortLines", "Sort Lines"), - act("code.reverseLines", "Reverse Lines"), - SEP, - act("editor.toggleColumnSelection", "Column Selection Mode"), - SEP, - macros(), - bookmarks(), - ] - } else { - // GTK/Win32 accelerators would swallow these keys before the webview, so - // they are plain items routed to `document.execCommand` by the frontend. - vec![ - hinted("edit.undo", "Undo", "Ctrl+Z"), - hinted("edit.redo", "Redo", "Ctrl+Shift+Z"), - SEP, - hinted("edit.cut", "Cut", "Ctrl+X"), - hinted("edit.copy", "Copy", "Ctrl+C"), - hinted("edit.paste", "Paste", "Ctrl+V"), - act("code.pasteFromHistory", "Paste from History…"), - act("code.pasteAsPlainText", "Paste as Plain Text"), - hinted("edit.selectAll", "Select All", "Ctrl+A"), - SEP, - find, - SEP, - act("editor.copyPath", "Copy Path"), - act("editor.copyReference", "Copy Reference"), - SEP, - act("code.sortLines", "Sort Lines"), - act("code.reverseLines", "Reverse Lines"), - SEP, - act("editor.toggleColumnSelection", "Column Selection Mode"), - SEP, - macros(), - bookmarks(), - ] - }; - menus.push(sub("edit", "Edit", edit)); - - menus.push(sub( - "view", - "View", - vec![ - sub( - "toolWindows", - "Tool Windows", - vec![Entry::Dynamic(DYNAMIC_TOOL_WINDOWS), SEP, act("toolwindow.hideAll", "Hide All Tool Windows")], - ), - sub( - "appearance", - "Appearance", - vec![ - act("editor.toggleZen", "Enter Distraction Free Mode"), - act("window.toggleFullScreen", "Toggle Full Screen"), - toggle("view.toggleCompactMode", "Compact Mode"), - toggle("view.togglePresentationAssistant", "Presentation Assistant"), - SEP, - act("view.zoomIn", "Zoom In IDE"), - act("view.zoomOut", "Zoom Out IDE"), - act("view.resetZoom", "Reset IDE Zoom"), - SEP, - act("view.toggleTheme", "Toggle Light/Dark Theme"), - act("toolbar.customize", "Customize Main Toolbar…"), - SEP, - toggle("view.toggleToolbar", "Toolbar"), - toggle("view.toggleToolWindowBars", "Tool Window Bars"), - sub( - "navigationBar", - "Navigation Bar", - vec![ - toggle("view.navigationBarTop", "Top"), - toggle("view.navigationBarStatusBar", "Status Bar"), - toggle("view.navigationBarHidden", "Don't Show"), - ], - ), - toggle("view.toggleStatusBar", "Status Bar"), - sub("statusBarWidgets", "Status Bar Widgets", vec![Entry::Dynamic(DYNAMIC_STATUS_BAR_WIDGETS)]), - ], - ), - sub( - "activeEditor", - "Active Editor", - vec![ - act("editor.toggleSoftWrap", "Soft-Wrap"), - act("editor.toggleRenderedDocs", "Render Documentation Comments"), - ], - ), - SEP, - act("code.quickDefinition", "Quick Definition"), - act("code.quickTypeDefinition", "Quick Type Definition"), - SEP, - act("navigate.recentLocations", "Recent Locations"), - act("navigate.recentFiles", "Recent Files"), - act("localHistory.recentChanges", "Recent Changes"), - SEP, - act("diff.compareWithClipboard", "Compare with Clipboard"), - SEP, - act("view.quickSwitchScheme", "Quick Switch Scheme…"), - SEP, - act("editor.resetFontSize", "Reset Font Size"), - act("editor.resetFontSizeAll", "Reset Font Size in All Editors"), - SEP, - act("view.notifications", "Notifications"), - ], - )); - - menus.push(sub( - "navigate", - "Navigate", - vec![ - act("navigate.searchEverywhere", "Search Everywhere"), - act("navigate.gotoClass", "Class…"), - act("navigate.gotoFile", "File…"), - act("navigate.gotoSymbol", "Symbol…"), - act("navigate.gotoLine", "Line/Column…"), - SEP, - act("navigate.back", "Back"), - act("navigate.forward", "Forward"), - act("navigate.lastEditLocation", "Last Edit Location"), - act("navigate.nextEditLocation", "Next Edit Location"), - SEP, - act("navigate.declaration", "Declaration or Usages"), - act("navigate.implementation", "Implementation(s)"), - act("navigate.typeDeclaration", "Type Declaration"), - act("navigate.superMethod", "Super Method"), - act("navigate.gotoTest", "Test"), - act("navigate.relatedSymbol", "Related Symbol…"), - SEP, - act("navigate.fileStructure", "File Structure"), - act("navigate.showFilePath", "File Path"), - act("navigate.callHierarchy", "Call Hierarchy"), - act("navigate.typeHierarchy", "Type Hierarchy"), - act("navigate.customRegion", "Custom Folding…"), - SEP, - act("navigate.nextMethod", "Next Method"), - act("navigate.previousMethod", "Previous Method"), - SEP, - act("navigate.nextError", "Next Highlighted Error"), - act("navigate.prevError", "Previous Highlighted Error"), - SEP, - act("navigate.selectIn", "Select In…"), - ], - )); - - menus.push(sub( - "code", - "Code", - vec![ - sub( - "completion", - "Code Completion", - vec![ - act("code.completion", "Basic"), - act("code.smartTypeCompletion", "Smart Type"), - SEP, - act("code.cyclicExpandWord", "Cyclic Expand Word"), - act("code.cyclicExpandWordBackward", "Cyclic Expand Word (Backward)"), - ], - ), - act("code.parameterInfo", "Parameter Info"), - act("code.quickDocumentation", "Quick Documentation"), - act("code.expressionTypeInfo", "Expression Type Info"), - act("code.showErrorDescription", "Error Description"), - act("editor.contextInfo", "Context Info"), - act("code.showIntentions", "Show Context Actions"), - act("code.generate", "Generate…"), - act("code.overrideMethods", "Override Methods…"), - act("code.implementMethods", "Implement Methods…"), - SEP, - act("code.insertLiveTemplate", "Insert Live Template…"), - act("code.surroundWith", "Surround With…"), - act("code.surroundWithLiveTemplate", "Surround with Live Template…"), - act("code.unwrap", "Unwrap/Remove…"), - SEP, - act("code.reformat", "Reformat Code"), - act("code.autoIndentLines", "Auto-Indent Lines"), - act("code.optimizeImports", "Optimize Imports"), - act("code.rearrange", "Rearrange Code"), - act("code.cleanup", "Code Cleanup…"), - SEP, - act("code.commentLine", "Comment with Line Comment"), - act("code.commentBlock", "Comment with Block Comment"), - SEP, - act("code.extendSelection", "Extend Selection"), - act("code.shrinkSelection", "Shrink Selection"), - act("code.duplicateLine", "Duplicate Line or Selection"), - act("code.deleteLine", "Delete Line"), - act("code.moveStatementUp", "Move Statement Up"), - act("code.moveStatementDown", "Move Statement Down"), - act("code.moveElementLeft", "Move Element Left"), - act("code.moveElementRight", "Move Element Right"), - act("code.moveLineUp", "Move Line Up"), - act("code.moveLineDown", "Move Line Down"), - SEP, - sub( - "folding", - "Folding", - vec![ - act("code.foldToggle", "Expand/Collapse"), - act("code.foldAll", "Collapse All"), - act("code.unfoldAll", "Expand All"), - sub( - "expandToLevel", - "Expand to Level", - vec![ - act("code.expandToLevel1", "1"), - act("code.expandToLevel2", "2"), - act("code.expandToLevel3", "3"), - act("code.expandToLevel4", "4"), - act("code.expandToLevel5", "5"), - ], - ), - sub( - "expandAllToLevel", - "Expand All to Level", - vec![ - act("code.expandAllToLevel1", "1"), - act("code.expandAllToLevel2", "2"), - act("code.expandAllToLevel3", "3"), - act("code.expandAllToLevel4", "4"), - act("code.expandAllToLevel5", "5"), - ], - ), - SEP, - act("code.expandDocComments", "Expand Doc Comments"), - act("code.collapseDocComments", "Collapse Doc Comments"), - SEP, - act("code.collapseBlock", "Fold Code Block"), - act("code.foldSelection", "Fold Selection / Remove Region"), - ], - ), - SEP, - act("analyze.inspectCode", "Inspect Code…"), - sub( - "analyzeCode", - "Analyze Code", - vec![ - act("analyze.inspectFile", "Inspect Current File"), - act("analyze.locateDuplicates", "Locate Duplicates…"), - ], - ), - act("analyze.stackTrace", "Analyze Stack Trace or Thread Dump…"), - ], - )); - - menus.push(sub( - "refactor", - "Refactor", - vec![ - act("refactor.thisMenu", "Refactor This…"), - SEP, - act("refactor.rename", "Rename…"), - act("refactor.changeSignature", "Change Signature…"), - SEP, - act("refactor.extractVariable", "Introduce Variable…"), - act("refactor.extractConstant", "Introduce Constant…"), - act("refactor.extractField", "Introduce Field…"), - act("refactor.extractParameter", "Introduce Parameter…"), - act("refactor.extractMethod", "Extract Method…"), - act("refactor.extractInterface", "Extract Interface…"), - act("refactor.inline", "Inline…"), - SEP, - act("refactor.pullMembersUp", "Pull Members Up…"), - act("refactor.pushMembersDown", "Push Members Down…"), - SEP, - act("refactor.move", "Move…"), - act("project.copyElement", "Copy…"), - act("refactor.safeDelete", "Safe Delete…"), - ], - )); - - menus.push(sub( - "build", - "Build", - vec![ - Entry::Dynamic(DYNAMIC_FLUTTER_BUILD), - act("build.buildProject", "Build Project"), - act("build.buildModule", "Build Module"), - act("build.compileFile", "Recompile"), - act("build.rebuildProject", "Rebuild Project"), - SEP, - act("build.buildArtifacts", "Build Artifacts"), - ], - )); - - menus.push(sub( - "run", - "Run", - vec![ - act("run.run", "Run"), - act("run.debug", "Debug"), - act("run.runContext", "Run Context Configuration"), - act("run.debugContext", "Debug Context Configuration"), - act("run.coverage", "Run with Coverage"), - act("run.profile", "Profile"), - act("run.stop", "Stop"), - SEP, - act("run.chooseConfig", "Run…"), - act("run.chooseDebugConfig", "Debug…"), - act("runAnything.show", "Run Anything…"), - act("run.editConfigs", "Edit Configurations…"), - act("run.updateApplication", "Update Application"), - act("debug.attachToProcess", "Attach to Process…"), - SEP, - act("debug.resume", "Resume Program"), - act("debug.pause", "Pause Program"), - act("debug.stepOver", "Step Over"), - act("debug.forceStepOver", "Force Step Over"), - act("debug.stepInto", "Step Into"), - act("debug.forceStepInto", "Force Step Into"), - act("debug.smartStepInto", "Smart Step Into"), - act("debug.stepOut", "Step Out"), - act("debug.runToCursor", "Run to Cursor"), - act("debug.forceRunToCursor", "Force Run to Cursor"), - act("debug.showExecutionPoint", "Show Execution Point"), - act("debug.resetFrame", "Reset Frame"), - act("debug.evaluate", "Evaluate Expression…"), - act("debug.quickEvaluate", "Quick Evaluate Expression"), - sub( - "debuggingActions", - "Debugging Actions", - vec![act("debug.reloadChangedClasses", "Reload Changed Classes")], - ), - SEP, - act("coverage.hide", "Hide Coverage"), - SEP, - act("debug.toggleBreakpoint", "Toggle Line Breakpoint"), - act("debug.toggleTemporaryBreakpoint", "Toggle Temporary Line Breakpoint"), - act("debug.toggleMethodBreakpoint", "Toggle Method Breakpoint"), - act("debug.toggleFieldWatchpoint", "Toggle Field Watchpoint"), - act("debug.viewBreakpoints", "View Breakpoints…"), - ], - )); - - menus.push(sub( - "git", - "Git", - vec![ - act("vcs.commit", "Commit…"), - act("vcs.push", "Push…"), - act("vcs.update", "Update Project…"), - act("vcs.pull", "Pull…"), - act("vcs.fetch", "Fetch"), - act("vcs.unshallow", "Fetch Full History"), - SEP, - // Operation items (Abort Merge, Continue Rebase…) are enabled only while it is in progress. - act("vcs.merge", "Merge…"), - act("vcs.merge.abort", "Abort Merge"), - act("vcs.rebase", "Rebase…"), - act("vcs.rebase.abort", "Abort Rebase"), - act("vcs.rebase.continue", "Continue Rebase"), - act("vcs.rebase.skip", "Skip Commit"), - act("vcs.resolveConflicts", "Resolve Conflicts…"), - SEP, - act("vcs.branches", "Branches…"), - act("vcs.newBranch", "New Branch…"), - act("vcs.newTag", "New Tag…"), - act("vcs.resetHead", "Reset HEAD…"), - SEP, - act("vcs.newWorktree", "New Worktree…"), - act("vcs.worktrees", "Worktrees…"), - SEP, - act("vcs.showLog", "Show Git Log"), - sub( - "gitPatch", - "Patch", - vec![ - act("vcs.createPatch", "Create Patch…"), - act("vcs.applyPatch", "Apply Patch…"), - act("vcs.applyPatchFromClipboard", "Apply Patch from Clipboard…"), - ], - ), - sub( - "gitUncommittedChanges", - "Uncommitted Changes", - vec![ - act("vcs.shelve", "Shelve Changes…"), - act("vcs.showShelf", "Show Shelf"), - act("vcs.stash", "Stash Changes…"), - act("vcs.showStashes", "Show Stash"), - act("vcs.unstash", "Unstash Changes…"), - act("vcs.rollback", "Rollback…"), - ], - ), - sub( - "gitCurrentFile", - "Current File", - vec![ - act("vcs.addToVcs", "Add to VCS"), - SEP, - act("vcs.annotate", "Annotate with Git Blame"), - act("vcs.showDiff", "Show Diff"), - act("vcs.compareWithBranch", "Compare with Branch or Revision…"), - act("vcs.showHistory", "Show History"), - act("vcs.showHistoryForSelection", "Show History for Selection"), - SEP, - act("vcs.localHistory", "Local History"), - act("localHistory.putLabel", "Put Label…"), - ], - ), - SEP, - sub( - "gitHub", - "GitHub", - vec![ - act("github.pullRequests", "View Pull Requests"), - act("github.createPullRequest", "Create Pull Request…"), - act("github.checkoutPullRequest", "Checkout Pull Request…"), - act("github.openInBrowser", "Open on GitHub"), - ], - ), - act("vcs.manageRemotes", "Manage Remotes…"), - act("vcs.clone", "Clone…"), - SEP, - act("vcs.operations", "VCS Operations Popup…"), - SEP, - act("vcs.revert.continue", "Continue Revert"), - act("vcs.revert.abort", "Abort Revert"), - act("vcs.cherryPick.continue", "Continue Cherry-Pick"), - act("vcs.cherryPick.abort", "Abort Cherry-Pick"), - ], - )); - - let mut tools = vec![ - act("http.newRequest", "New HTTP Request"), - act("http.showToolWindow", "HTTP Client"), - SEP, - act("db.showToolWindow", "Database"), - act("db.newDataSource", "New Data Source…"), - act("db.openConsole", "Open Query Console"), - SEP, - act("ssh.startSession", "Start SSH Session…"), - act("ssh.configurations", "SSH Configurations…"), - sub( - "deployment", - "Deployment", - vec![ - act("deployment.uploadToDefault", "Upload to Default Server"), - act("deployment.uploadTo", "Upload to…"), - act("deployment.downloadFromDefault", "Download from Default Server"), - act("deployment.downloadFrom", "Download from…"), - act("deployment.syncWith", "Sync with Deployed…"), - act("deployment.deleteFromServer", "Delete from Server"), - SEP, - act("deployment.toggleAutoUpload", "Automatic Upload"), - act("deployment.browseRemoteHost", "Browse Remote Host"), - act("deployment.openInBrowser", "Open in Browser"), - act("deployment.configure", "Configuration…"), - ], - ), - SEP, - act("vim.toggle", "Vim"), - Entry::Dynamic(DYNAMIC_PLUGIN_TOOLS), - ]; - if !mac { - tools.extend([ - SEP, - act("app.installCli", "Install 'openidea' Command"), - act("app.uninstallCli", "Uninstall 'openidea' Command"), - ]); - } - menus.push(sub("tools", "Tools", tools)); - - let mut window = Vec::new(); - if mac { - window.extend([Entry::Native(Native::Minimize), Entry::Native(Native::Zoom), SEP]); - } - window.extend([ - sub( - "toolWindowLayouts", - "Tool Window Layouts", - vec![ - toggle("layout.restoreDefault", "Restore Default Layout"), - Entry::Dynamic(DYNAMIC_LAYOUTS), - SEP, - act("layout.restoreCurrent", "Restore Current Layout"), - act("layout.saveCurrent", "Save Changes in Current Layout"), - act("layout.save", "Save Current Layout as…"), - ], - ), - SEP, - sub( - "activeToolWindow", - "Active Tool Window", - vec![ - act("toolwindow.hideActive", "Hide Active Tool Window"), - act("toolwindow.hideSide", "Hide Side Tool Windows"), - act("toolwindow.maximize", "Maximize Tool Window"), - act("toolwindow.closeContent", "Close Active Tab"), - sub( - "resizeToolWindow", - "Resize", - vec![ - act("toolwindow.resizeLeft", "Stretch to Left"), - act("toolwindow.resizeRight", "Stretch to Right"), - act("toolwindow.resizeUp", "Stretch to Top"), - act("toolwindow.resizeDown", "Stretch to Bottom"), - ], - ), - SEP, - act("toolwindow.jumpToLast", "Jump to Last Tool Window"), - act("toolwindow.focusEditor", "Focus Editor"), - ], - ), - sub( - "editorTabs", - "Editor Tabs", - vec![ - act("editor.nextTab", "Select Next Tab"), - act("editor.prevTab", "Select Previous Tab"), - SEP, - act("editor.pinTab", "Pin Tab"), - act("editor.closeTab", "Close Tab"), - act("editor.closeOtherTabs", "Close Other Tabs"), - act("editor.closeAllTabs", "Close All Tabs"), - act("editor.reopenClosedTab", "Reopen Closed Tab"), - SEP, - act("editor.splitRight", "Split Right"), - act("editor.splitDown", "Split Down"), - act("editor.unsplit", "Unsplit"), - act("editor.moveToOppositeGroup", "Move to Opposite Group"), - act("editor.openInOppositeGroup", "Open in Opposite Group"), - act("editor.changeSplitOrientation", "Change Splitter Orientation"), - act("editor.unsplitAll", "Unsplit All"), - act("editor.nextSplitter", "Go to Next Splitter"), - act("editor.prevSplitter", "Go to Previous Splitter"), - ], - ), - SEP, - act("window.new", "New Window"), - act("window.mergeAllWindows", "Merge All Project Windows"), - act("window.detachTab", "Move Tab to New Window"), - act("window.nextTab", "Next Project Tab"), - act("window.previousTab", "Previous Project Tab"), - ]); - // ⌘` is macOS's window cycling; elsewhere Ctrl+` is Quick Switch Scheme and the keymap's - // Ctrl+Alt+] / Ctrl+Alt+[ switch windows. - if mac { - window.extend([ - accel("window.next", "Next Project Window", "Cmd+`"), - accel("window.previous", "Previous Project Window", "Cmd+Shift+`"), - ]); - } else { - window.extend([act("window.next", "Next Project Window"), act("window.previous", "Previous Project Window")]); - } - if mac { - window.extend([SEP, Entry::Native(Native::BringAllToFront)]); - } - menus.push(sub("window", "Window", window)); - - let mut help = vec![ - act("navigate.findAction", "Find Action…"), - act("help.keymapReference", "Keymap Reference"), - SEP, - act("app.whatsNew", "What's New"), - act("help.showLog", show_log), - ]; - if !mac { - help.extend([act("app.checkForUpdates", "Check for Updates…"), SEP, act("app.about", "About OpenIDEA")]); - } - menus.push(sub("help", "Help", help)); - menus -} - -/// What a clicked menu item asks the frontend to do. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct MenuRoute { - pub action: String, - pub arg: Option, -} /// Payload of [`MENU_EVENT`]: the route, and the window that was in front when the item was /// chosen if the action runs in another one (a Settings window's project window). @@ -931,181 +38,12 @@ pub struct MenuEvent<'a> { pub return_to: Option<&'a str>, } -/// Maps a clicked item id to the action to run. `None` for ids that are not -/// IDE items (native roles, placeholders). -pub fn route(spec: &[Entry], id: &str) -> Option { - if let Some(path) = id.strip_prefix(RECENT_PREFIX) { - return Some(MenuRoute { action: OPEN_RECENT_ACTION.into(), arg: Some(path.into()) }); - } - if let Some(rest) = id.strip_prefix(DYNAMIC_PREFIX) { - let (action, arg) = match rest.split_once('|') { - Some((action, arg)) => (action, Some(arg.to_owned())), - None => (rest, None), - }; - return (!action.is_empty()).then(|| MenuRoute { action: action.into(), arg }); - } - action_ids(spec).into_iter().any(|a| a == id).then(|| MenuRoute { action: id.into(), arg: None }) -} - -/// `entries` without the action `id` (and a separator it leaves doubled or trailing). -pub fn without_action(entries: Vec, id: &str) -> Vec { - let mut out: Vec = Vec::with_capacity(entries.len()); - for e in entries { - match e { - Entry::Action { id: a, .. } if a == id => {} - Entry::Submenu { id: sid, label, children } => { - out.push(Entry::Submenu { id: sid, label, children: without_action(children, id) }) - } - Entry::Separator if matches!(out.last(), None | Some(Entry::Separator)) => {} - e => out.push(e), - } - } - if matches!(out.last(), Some(Entry::Separator)) { - out.pop(); - } - out -} - -/// Every action id reachable from the spec (with duplicates). -pub fn action_ids(spec: &[Entry]) -> Vec<&'static str> { - fn walk(entries: &[Entry], out: &mut Vec<&'static str>) { - for e in entries { - match e { - Entry::Submenu { children, .. } => walk(children, out), - Entry::Action { id, .. } => out.push(id), - _ => {} - } - } - } - let mut out = Vec::new(); - walk(spec, &mut out); - out -} - -/// Localised labels and keymap accelerators, pushed by the frontend. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct MenuConfig { - pub locale: String, - /// `menu.` → label (ids of submenus, actions and `native.*` roles). - pub labels: HashMap, - /// Action id → native accelerator of its first keymap binding, e.g. `Shift+Meta+O`. - /// Absent when that binding has no native form (chord, double modifier). - pub accelerators: HashMap, - /// [`Entry::Dynamic`] slot → its items, already localised. - #[serde(default)] - pub dynamic: HashMap>, - /// Ids of the toggle actions currently on. - #[serde(default)] - pub checked: Vec, -} - -/// An item of a frontend-listed menu slot. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct DynamicItem { - pub action: String, - pub arg: Option, - pub label: String, - /// Drawn with a check mark in this state; `None` for a plain item. - #[serde(default)] - pub checked: Option, -} - -impl DynamicItem { - /// Native menu item id, decoded again by [`route`]. - pub fn item_id(&self) -> String { - match &self.arg { - Some(arg) => format!("{DYNAMIC_PREFIX}{}|{arg}", self.action), - None => format!("{DYNAMIC_PREFIX}{}", self.action), - } - } - - fn model(&self) -> MenuNode { - MenuNode::Action { - id: self.action.clone(), - label: self.label.clone(), - hint: None, - arg: self.arg.clone(), - checked: self.checked, - } - } - - fn render(&self, config: &MenuConfig) -> RenderedItem { - RenderedItem::Action { - id: self.item_id(), - text: self.label.clone(), - accel: config.dynamic_accelerator(self).map(Into::into), - checked: self.checked, - } - } -} - -struct LayoutMenu<'a> { - id: String, - name: &'a str, - current: bool, - items: Vec>, -} - -impl MenuConfig { - fn label(&self, id: &str, default: &str) -> String { - self.labels.get(&format!("menu.{id}")).cloned().unwrap_or_else(|| default.to_owned()) - } - - fn dynamic_items(&self, slot: &str) -> &[DynamicItem] { - self.dynamic.get(slot).map(Vec::as_slice).unwrap_or_default() - } - - fn layout_menus(&self) -> Vec> { - self.dynamic_items(DYNAMIC_LAYOUTS) - .iter() - .filter_map(|layout| { - let name = layout.arg.as_deref()?; - let current = layout.checked.unwrap_or_default(); - let command = |action: &str, label_key, fallback| { - Some(DynamicItem { - action: action.into(), - arg: Some(name.into()), - label: self.label(label_key, fallback), - checked: None, - }) - }; - let mut items = if current { - vec![ - command("layout.restore", "layout.restoreNamed", "Restore"), - command("layout.saveCurrent", "layout.saveNamed", "Save Changes"), - ] - } else { - vec![command("layout.restore", "layout.applyNamed", "Apply")] - }; - items.extend([ - command("layout.rename", "layout.renameNamed", "Rename…"), - None, - command("layout.delete", "layout.deleteNamed", "Delete…"), - ]); - Some(LayoutMenu { id: format!("layout:{name}"), name, current, items }) - }) - .collect() - } - - /// The keymap accelerator shown on the item of action `id`. - fn accelerator(&self, id: &str) -> Option<&str> { - self.accelerators.get(id).map(String::as_str).filter(|a| !a.is_empty()) - } - - /// A dynamic item's accelerator: the action's, unless the item carries an argument. - fn dynamic_accelerator(&self, item: &DynamicItem) -> Option<&str> { - item.arg.is_none().then(|| self.accelerator(&item.action)).flatten() - } - - /// Item text: the label, with the spec's hint after a tab (Windows/Linux edit items). - pub fn item_text(&self, id: &str, default: &str, hint: Option<&str>) -> String { - let label = self.label(id, default); - match hint { - Some(hint) => format!("{label}\t{hint}"), - None => label, - } +fn render_dynamic(item: &DynamicItem, config: &MenuConfig) -> RenderedItem { + RenderedItem::Action { + id: item.item_id(), + text: item.label.clone(), + accel: config.dynamic_accelerator(item).map(Into::into), + checked: item.checked, } } @@ -1121,19 +59,6 @@ pub struct MenuState { pub remote_recent: Mutex>, } -/// A recent Remote Development project (SSH, WSL, Dev Container), kept by the frontend: Open -/// Recent lists it among the local projects, as Manage Projects does. -#[derive(Debug, Clone, PartialEq, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct RemoteRecent { - /// `ssh://host/path`, `wsl://Ubuntu/path`…: what `file.openRecentProject` gets back. - pub location: String, - pub name: String, - /// Where it lives, as shown after the name (`me@host:/srv/app`). - pub detail: String, - pub opened_at_ms: f64, -} - /// Stores the remote recent list; `false` when it is unchanged. pub fn store_remote_recent(state: &MenuState, next: Vec) -> bool { let mut current = state.remote_recent.lock(); @@ -1213,35 +138,6 @@ pub fn apply_disabled(app: &AppHandle, disabled: &HashSet } } -pub struct RecentItem { - pub path: String, - pub label: String, -} - -/// The local and remote recent projects, most recently opened first. -pub fn recent_items( - recent: &[ide_workspace::RecentProject], - remote: &[RemoteRecent], - home: Option<&Path>, -) -> Vec { - let local = recent.iter().map(|p| { - let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) { - Some(rest) => format!("~/{}", rest.display()), - None => p.path.display().to_string(), - }; - let item = - RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) }; - (p.opened_at_ms, item) - }); - let remote = remote.iter().map(|r| { - (r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) }) - }); - let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect(); - // Stable: the local list's own order holds among equal times. - items.sort_by(|a, b| b.0.total_cmp(&a.0)); - items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect() -} - /// One top-level menu, as it will actually be drawn. #[derive(Debug, Clone, PartialEq, Eq)] struct RenderedMenu { @@ -1329,7 +225,7 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) - items: layout .items .into_iter() - .map(|item| item.map_or(RenderedItem::Separator, |item| item.render(config))) + .map(|item| item.map_or(RenderedItem::Separator, |item| render_dynamic(&item, config))) .collect(), } })); @@ -1341,12 +237,14 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) - id: FLUTTER_BUILD_MENU.into(), title: config.label(FLUTTER_BUILD_MENU, "Flutter"), current: false, - items: items.iter().map(|item| item.render(config)).collect(), + items: items.iter().map(|item| render_dynamic(item, config)).collect(), }); out.push(RenderedItem::Separator); } } - Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(|item| item.render(config))), + Entry::Dynamic(slot) => { + out.extend(config.dynamic_items(slot).iter().map(|item| render_dynamic(item, config))) + } Entry::Native(kind) => { out.push(RenderedItem::Native { kind: *kind, text: config.label(kind.key(), kind.default_label()) }) } @@ -1627,104 +525,6 @@ fn patch_menu( true } -/// A menu entry for a menu bar drawn by the frontend (Windows title bar). -/// Labels are the English defaults; the frontend localises them like the native menu. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase", tag = "kind")] -pub enum MenuNode { - Submenu { - id: String, - label: String, - /// Saved layout selection, unset for ordinary submenus. - #[serde(skip_serializing_if = "Option::is_none")] - current: Option, - children: Vec, - }, - /// Runs `id` with `arg`. Items with an `arg` (Open Recent) carry their final label. - /// `checked` is the state of a frontend-listed toggle (Status Bar Widgets). Spec toggles - /// leave it unset: the frontend menu reads their state from the action (`toggled`), the - /// source [`MenuConfig::checked`] is built from for the native menu. - Action { - id: String, - label: String, - hint: Option, - arg: Option, - checked: Option, - }, - /// A disabled placeholder such as "No Recent Projects". - Placeholder { - id: String, - label: String, - }, - Separator, -} - -/// The spec as [`MenuNode`]s; native role items (macOS only) are left out. -pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec { - let mut out = Vec::new(); - for e in spec { - match e { - Entry::Submenu { id, label, children } => out.push(MenuNode::Submenu { - id: (*id).into(), - label: (*label).into(), - current: None, - children: model(children, recent, config), - }), - Entry::Dynamic(DYNAMIC_LAYOUTS) => { - let layouts = config.layout_menus(); - if !layouts.is_empty() { - out.push(MenuNode::Separator); - } - out.extend(layouts.into_iter().map(|layout| { - MenuNode::Submenu { - id: layout.id, - label: layout.name.into(), - current: Some(layout.current), - children: layout - .items - .into_iter() - .map(|item| item.map_or(MenuNode::Separator, |item| item.model())) - .collect(), - } - })); - } - Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => { - let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD); - if !items.is_empty() { - out.push(MenuNode::Submenu { - id: FLUTTER_BUILD_MENU.into(), - label: "Flutter".into(), - current: None, - children: items.iter().map(DynamicItem::model).collect(), - }); - out.push(MenuNode::Separator); - } - } - Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(DynamicItem::model)), - Entry::Action { id, label, hint, .. } => out.push(MenuNode::Action { - id: (*id).into(), - label: (*label).into(), - hint: hint.map(Into::into), - arg: None, - checked: None, - }), - Entry::Native(_) => {} - Entry::Separator => out.push(MenuNode::Separator), - Entry::RecentProjects if recent.is_empty() => { - out.push(MenuNode::Placeholder { id: "recent.none".into(), label: "No Recent Projects".into() }) - } - Entry::RecentProjects => out.extend(recent.iter().map(|r| MenuNode::Action { - id: OPEN_RECENT_ACTION.into(), - label: r.label.clone(), - hint: None, - arg: Some(r.path.clone()), - checked: None, - })), - } - } - out -} - /// Whether the OS menu bar is used. Windows and Linux project windows are /// frameless and draw IDEA's hamburger menu in their own title bar instead. pub fn native_menu_bar() -> bool { @@ -1843,6 +643,7 @@ fn register_macos_windows_menu(app: &AppHandle) { mod tests { use super::*; use std::collections::{BTreeSet, HashSet}; + use std::path::Path; const ALL_OS: [Os; 3] = [Os::Mac, Os::Windows, Os::Linux]; diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 48575966c8..f00a6c832a 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -167,15 +167,7 @@ impl AppState { } pub fn record_project(&self, project: &Project) -> IdeResult<()> { - let info = ide_host::ops::project::info(project); - let attached = info.workspace.as_ref().is_some_and(|w| !w.is_container(&project.root)); - let branch = if attached { - None - } else { - project.repos.read().primary().and_then(|r| r.branch_info().ok()).and_then(|b| b.head) - }; - self.recent.touch(&project.root, branch)?; - self.recent.rename(&project.root, Some(&info.display_name))?; + ide_host::ops::project::record_recent(&self.recent, project)?; crate::jump_list::refresh(&self.app, self.recent.list()); Ok(()) } diff --git a/src/features/app/windows.ts b/src/features/app/windows.ts index d9cf8afd41..6bbe0b4e46 100644 --- a/src/features/app/windows.ts +++ b/src/features/app/windows.ts @@ -10,6 +10,7 @@ import { executeAction, type Action } from "@/platform/actions"; import { t, tx } from "@/platform/i18n"; import { call, commands, isCancelled, isTauri } from "@/platform/ipc"; +import { isWebMode } from "@/platform/webBridge"; import { basename, confirmLeaveProject, @@ -159,6 +160,13 @@ export async function openProjectInWindow(path: string, newWindow: boolean, file if (desktopOnly()) return; const s = useProject.getState(); const inNew = newWindow || s.project !== null || s.lightEdit; + if (inNew && isWebMode()) { + const url = new URL(window.location.href); + url.searchParams.set("project", path); + url.searchParams.set("newWindow", "1"); + const opened = window.open(url.toString(), "_blank", "noopener"); + if (opened) return; + } try { const outcome = await openProjectWindow(path, inNew, files); if (outcome.kind === "current" && (await openHere(path))) await openInEditor(files); diff --git a/src/features/settings/index.ts b/src/features/settings/index.ts index 9d307e7594..515969603c 100644 --- a/src/features/settings/index.ts +++ b/src/features/settings/index.ts @@ -14,6 +14,7 @@ */ import { registerActions } from "@/platform/actions"; import { call, commands, isTauri } from "@/platform/ipc"; +import { isWebMode } from "@/platform/webBridge"; import { lazyWhen } from "@/ui"; import { useProject } from "@/platform/project"; import { provideSettingsSearchIndex, registerOverlay } from "@/workbench/contributions"; @@ -49,7 +50,7 @@ const separateWindow = () => useProject.getState().settings?.appearance?.setting /** The native Settings window when it is enabled and the backend can make one, else the dialog. */ async function showSettings(page?: string, newProjects = false) { - if (isTauri() && separateWindow()) { + if (isTauri() && !isWebMode() && separateWindow()) { try { await call(commands.windowOpenSettings(page ?? null, newProjects, windowBackgroundHex())); return; diff --git a/src/main.tsx b/src/main.tsx index 7fbdbe37c2..0a8d868cdc 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,6 +1,8 @@ import { auxiliaryWindow } from "./platform/auxWindow"; +import { initWebRuntime } from "./platform/webBridge"; import { installCommonWindowBoot } from "./windowBoot"; +await initWebRuntime(); await installCommonWindowBoot(); // Auxiliary windows (`settings-`, `comparison--`, `diff--`, diff --git a/src/platform/choosePath.ts b/src/platform/choosePath.ts index 4a2e67c39e..909d5b67f2 100644 --- a/src/platform/choosePath.ts +++ b/src/platform/choosePath.ts @@ -1,6 +1,7 @@ import { isTauri } from "@/platform/ipc"; import { isRemoteWindow } from "@/platform/remote"; import type { DialogFilter, SaveDialogOptions } from "@/platform/dialog"; +import { isWebMode } from "@/platform/webBridge"; export interface ChoosePathOptions { directory: boolean; @@ -18,6 +19,8 @@ export interface HostPathOptions extends ChoosePathOptions { type HostChooser = (opts: HostPathOptions) => Promise; let hostChooser: HostChooser | null = null; +const shouldUseHostChooser = () => isRemoteWindow() || isWebMode(); + /** * Registers the in-app chooser that browses the remote host (the workbench's, in `inputDialogs`): * the desktop's own dialog would show this machine's files. @@ -31,11 +34,11 @@ export function registerHostPathChooser(chooser: HostChooser): () => void { /** * File / folder chooser for a path on the host this window's commands run on: the desktop's dialog - * locally, the in-app chooser in a remote window. Null when cancelled or outside Tauri. + * locally, the in-app chooser in a remote or web-server window. Null when cancelled or outside Tauri. */ export async function choosePath(opts: ChoosePathOptions, signal?: AbortSignal): Promise { if (!isTauri() || signal?.aborted) return null; - if (isRemoteWindow()) return (await hostChooser?.({ ...opts, signal }))?.[0] ?? null; + if (shouldUseHostChooser()) return (await hostChooser?.({ ...opts, signal }))?.[0] ?? null; // Lazy on purpose: loading platform/dialog starts its GTK capability probe at module load. const { open } = await import("@/platform/dialog"); if (signal?.aborted) return null; @@ -46,7 +49,7 @@ export async function choosePath(opts: ChoosePathOptions, signal?: AbortSignal): /** Pick multiple existing paths on the project host. */ export async function choosePaths(opts: ChoosePathOptions): Promise { if (!isTauri()) return []; - if (isRemoteWindow()) return (await hostChooser?.({ ...opts, multiple: true })) ?? []; + if (shouldUseHostChooser()) return (await hostChooser?.({ ...opts, multiple: true })) ?? []; const { open } = await import("@/platform/dialog"); const picked = await open({ ...opts, multiple: true }); return typeof picked === "string" ? [picked] : (picked ?? []); @@ -55,7 +58,7 @@ export async function choosePaths(opts: ChoosePathOptions): Promise { /** Choose a destination on the project host and confirm replacement if it exists. */ export async function chooseSavePath(opts: SaveDialogOptions, signal?: AbortSignal): Promise { if (signal?.aborted) return null; - if (isRemoteWindow()) + if (shouldUseHostChooser()) return (await hostChooser?.({ ...opts, directory: false, save: true, ...(signal && { signal }) }))?.[0] ?? null; const { save } = await import("@/platform/dialog"); return signal?.aborted ? null : save(opts); diff --git a/src/platform/clipboard.ts b/src/platform/clipboard.ts index 0f0ea4bb88..059d85f650 100644 --- a/src/platform/clipboard.ts +++ b/src/platform/clipboard.ts @@ -2,17 +2,20 @@ import { call, commands, isTauri } from "./ipc"; import { ipcPath } from "./paths"; import { toBase64 } from "./base64"; import { usePlatform } from "./platformInfo"; +import { isWebMode } from "./webBridge"; + +const isDesktop = () => isTauri() && !isWebMode(); /** Native menu actions and async work can outlive WebKit's user activation. */ export async function writeClipboardText(text: string): Promise { - if (isTauri()) await call(commands.clipboardWriteText(text)); + if (isDesktop()) await call(commands.clipboardWriteText(text)); else await navigator.clipboard.writeText(text); } /** Start the browser write before awaiting image conversion, preserving Safari user activation. */ export async function writeClipboardPng(png: Promise): Promise { void png.catch(() => {}); - if (isTauri()) { + if (isDesktop()) { const bytes = new Uint8Array(await (await png).arrayBuffer()); await call(commands.clipboardWriteImage(toBase64(bytes))); } else { @@ -28,7 +31,7 @@ export async function writeClipboardPng(png: Promise): Promise { * gives no text there, and WebView2 prompts for it. Rejects when the WebView refuses. */ export async function readClipboardPlainText(): Promise { - if (isTauri()) { + if (isDesktop()) { const text = await call(commands.clipboardText()).catch(() => undefined); if (text != null) return text; // WebKit on macOS makes the user confirm the read with a "Paste" callout; the backend found no text. @@ -39,7 +42,7 @@ export async function readClipboardPlainText(): Promise { /** The clipboard's image as base64 PNG, read natively; null when it holds none or outside the desktop app. */ export async function readClipboardPng(): Promise { - if (!isTauri()) return null; + if (!isDesktop()) return null; const url = await call(commands.clipboardImage()); return url ? url.slice(url.indexOf(",") + 1) : null; } @@ -53,7 +56,7 @@ export async function readClipboardText( formatFiles: FormatFiles = rawPaths, ): Promise { const text = transfer ? transfer.getData("text/plain") : await readClipboardPlainText().catch(() => ""); - if ((text && formatFiles === rawPaths) || (transfer && !hasClipboardFiles(transfer)) || !isTauri()) return text; + if ((text && formatFiles === rawPaths) || (transfer && !hasClipboardFiles(transfer)) || !isDesktop()) return text; let paths: string[]; try { paths = await call(commands.clipboardFileList()); diff --git a/src/platform/dialog.ts b/src/platform/dialog.ts index 7410be6712..609183473a 100644 --- a/src/platform/dialog.ts +++ b/src/platform/dialog.ts @@ -15,10 +15,16 @@ import { export type { SaveDialogOptions, DialogFilter }; import { call, commands } from "@/platform/ipc"; +import { choosePath, choosePaths, chooseSavePath } from "@/platform/choosePath"; +import { isWebMode } from "@/platform/webBridge"; let needsGtk: boolean | undefined; // Asked once when the module loads, so a picker only waits for the answer if it opens first. const probe = (async () => { + if (isWebMode()) { + needsGtk = false; + return; + } try { needsGtk = await commands.fileDialogNeedsGtk(); } catch { @@ -58,12 +64,31 @@ async function gtkPick(options: { } export async function open(options: T = {} as T): Promise> { + if (isWebMode()) { + const base = { + directory: options.directory ?? false, + title: options.title ?? (options.directory ? "Open Folder" : "Open File"), + defaultPath: options.defaultPath, + filters: options.filters, + }; + if (options.multiple) { + const paths = await choosePaths(base); + return (paths.length ? paths : null) as OpenDialogReturn; + } + return (await choosePath(base)) as OpenDialogReturn; + } if (needsGtk === false || !(await pluginDialogsUnavailable())) return pluginOpen(options); const paths = await gtkPick(options); return (options.multiple ? paths : (paths?.[0] ?? null)) as OpenDialogReturn; } export async function save(options: SaveDialogOptions = {}): Promise { + if (isWebMode()) { + return chooseSavePath({ + ...options, + title: options.title ?? "Save File", + }); + } if (needsGtk === false || !(await pluginDialogsUnavailable())) return pluginSave(options); return (await gtkPick({ ...options, save: true }))?.[0] ?? null; } diff --git a/src/platform/dragOut.ts b/src/platform/dragOut.ts index 19951d176c..4c6d75b1cd 100644 --- a/src/platform/dragOut.ts +++ b/src/platform/dragOut.ts @@ -5,6 +5,7 @@ */ import { call, commands, isTauri } from "./ipc"; import { isRemoteWindow } from "./remote"; +import { isWebMode } from "./webBridge"; /** The running drag, until it ends or the next press shows none is live. */ let running: object | null = null; @@ -14,7 +15,7 @@ const pressed = () => { /** Whether files can be dragged out of this window. */ export function canDragOut(): boolean { - return isTauri() && !isRemoteWindow(); + return isTauri() && !isWebMode() && !isRemoteWindow(); } /** diff --git a/src/platform/fileManager.ts b/src/platform/fileManager.ts index f57b5eb9da..5c9d48976c 100644 --- a/src/platform/fileManager.ts +++ b/src/platform/fileManager.ts @@ -2,6 +2,7 @@ import type { RemoteTarget } from "./ipc"; import { call, commands, isTauri } from "./ipc"; import { usePlatform } from "./platformInfo"; import { useRemote } from "./remote"; +import { isWebMode } from "./webBridge"; function wslSharePath(path: string, target: RemoteTarget | null): string { if (target?.kind !== "wsl" || !path.startsWith("/")) return path; @@ -49,6 +50,7 @@ export function revealInFileManagerLabel(os = usePlatform.getState().os): string * Windows through their `\\wsl.localhost` share. */ export function canRevealInFileManager(target = windowTarget(), os = usePlatform.getState().os): boolean { + if (isWebMode()) return false; return target === null || (target.kind === "wsl" && os === "windows"); } @@ -60,7 +62,7 @@ export async function revealInFileManager( paths: string | readonly string[], target = windowTarget(), ): Promise { - if (!isTauri() || !canRevealInFileManager(target)) return false; + if (!isTauri() || isWebMode() || !canRevealInFileManager(target)) return false; const list = (typeof paths === "string" ? [paths] : paths).map((path) => fileManagerPath(path, undefined, target)); if (!list.length) return false; const { revealItemInDir } = await import("@tauri-apps/plugin-opener"); @@ -74,7 +76,7 @@ export async function revealInFileManager( * their server. */ export function canOpenWithSystemApp(target = windowTarget()): boolean { - return isTauri() && target === null; + return isTauri() && !isWebMode() && target === null; } /** diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index a87bfe160b..244e8a3f6c 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4046,5 +4046,11 @@ "The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.": "The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.", "Stop Backend and Open": "Stop Backend and Open", "Could not load the frames: {0}": "Could not load the frames: {0}", - "Allow all optional permissions": "Allow all optional permissions" + "Allow all optional permissions": "Allow all optional permissions", + "Connection to OpenIDEA server lost. Reconnecting…": "Connection to OpenIDEA server lost. Reconnecting…", + "Save File": "Save File", + "Not connected to OpenIDEA server": "Not connected to OpenIDEA server", + "Command failed": "Command failed", + "This OpenIDEA session is open in another browser tab.": "This OpenIDEA session is open in another browser tab.", + "Take Over": "Take Over" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index d1f277f3d5..d793fb383e 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10438,5 +10438,11 @@ "Extracted {written} embedded images": "已提取 {written} 张嵌入图片", "Saved to {name}/.": "已保存到 {name}/。", "Could not extract embedded images": "无法提取嵌入的图片", - "{reason} No image links were changed. {written} image files were written to {name}/ before the operation stopped.": "{reason} 图片链接未更改。操作停止前已将 {written} 个图片文件写入 {name}/。" + "{reason} No image links were changed. {written} image files were written to {name}/ before the operation stopped.": "{reason} 图片链接未更改。操作停止前已将 {written} 个图片文件写入 {name}/。", + "Connection to OpenIDEA server lost. Reconnecting…": "与 OpenIDEA 服务器的连接已断开,正在重新连接…", + "Save File": "保存文件", + "Not connected to OpenIDEA server": "未连接到 OpenIDEA 服务器", + "Command failed": "命令执行失败", + "This OpenIDEA session is open in another browser tab.": "此 OpenIDEA 会话已在另一个浏览器标签页中打开。", + "Take Over": "接管会话" } diff --git a/src/platform/openUrl.ts b/src/platform/openUrl.ts index 1cb0290f43..6763834f12 100644 --- a/src/platform/openUrl.ts +++ b/src/platform/openUrl.ts @@ -1,4 +1,5 @@ import { isTauri } from "./ipc"; +import { isWebMode } from "./webBridge"; const OPENABLE_PROTOCOLS = new Set(["http:", "https:", "mailto:"]); @@ -15,7 +16,7 @@ export function isOpenable(url: string): boolean { /** Opens a web or `mailto:` URL with the system handler (the default browser); other schemes are ignored. */ export async function openExternalUrl(url: string): Promise { if (!isOpenable(url)) return; - if (!isTauri()) { + if (!isTauri() || isWebMode()) { window.open(url, "_blank", "noopener"); return; } diff --git a/src/platform/platformInfo.ts b/src/platform/platformInfo.ts index 05fcb8a66a..1ff227bd8a 100644 --- a/src/platform/platformInfo.ts +++ b/src/platform/platformInfo.ts @@ -1,5 +1,6 @@ import { create } from "zustand"; import { commands, isTauri, type WindowButtonLayout } from "@/platform/ipc"; +import { isWebMode } from "@/platform/webBridge"; interface PlatformInfo { /** `macos` | `windows` | `linux` | `web`. */ @@ -30,14 +31,15 @@ export function guessOs(): "macos" | "windows" | "linux" | "web" { export const usePlatform = create(() => { const os = guessOs(); + const desktop = isTauri() && !isWebMode(); return { os, version: null, windowsBuildNumber: null, - overlayTitleBar: isTauri() && os === "macos", - framelessTitleBar: isTauri() && (os === "windows" || os === "linux"), + overlayTitleBar: desktop && os === "macos", + framelessTitleBar: desktop && (os === "windows" || os === "linux"), wayland: false, - windowButtons: DEFAULT_WINDOW_BUTTONS, + windowButtons: isWebMode() ? { left: [], right: [] } : DEFAULT_WINDOW_BUTTONS, }; }); @@ -45,14 +47,15 @@ export async function loadPlatformInfo() { if (!isTauri()) return; try { const info = await commands.appInfo(); + const web = isWebMode(); usePlatform.setState({ os: info.platform, version: info.version, windowsBuildNumber: info.windowsBuildNumber, - overlayTitleBar: info.platform === "macos", - framelessTitleBar: info.platform === "windows" || info.platform === "linux", - wayland: info.wayland, - windowButtons: info.windowButtons ?? DEFAULT_WINDOW_BUTTONS, + overlayTitleBar: !web && info.platform === "macos", + framelessTitleBar: !web && (info.platform === "windows" || info.platform === "linux"), + wayland: !web && info.wayland, + windowButtons: web ? { left: [], right: [] } : (info.windowButtons ?? DEFAULT_WINDOW_BUTTONS), }); } catch { /* keep the user-agent guess */ diff --git a/src/platform/systemFonts.ts b/src/platform/systemFonts.ts index 49e5a5ca36..f5f3bb2fd5 100644 --- a/src/platform/systemFonts.ts +++ b/src/platform/systemFonts.ts @@ -5,6 +5,7 @@ import { BUNDLED_MONO_FAMILY, BUNDLED_UI_FAMILY, discoverNerdFonts, noteInstalle import { create } from "zustand"; import { isTauri } from "@tauri-apps/api/core"; import { call, commands, type FontFamily } from "@/platform/ipc"; +import { isWebMode } from "./webBridge"; export type FontStatus = "idle" | "loading" | "ready" | "empty" | "error" | "browser"; export const bundledFonts: FontFamily[] = [ @@ -43,7 +44,7 @@ function fallback(status: "error" | "browser") { export function loadSystemFonts(refresh = false): Promise { if (pending) return pending; if (!refresh && useSystemFontStore.getState().status !== "idle") return Promise.resolve(); - if (!isTauri()) { + if (!isTauri() || isWebMode()) { fallback("browser"); return Promise.resolve(); } diff --git a/src/platform/webBridge.test.ts b/src/platform/webBridge.test.ts new file mode 100644 index 0000000000..bf1e0bd658 --- /dev/null +++ b/src/platform/webBridge.test.ts @@ -0,0 +1,284 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + encodeWebArgs, + initWebRuntime, + isWebMode, + resolveWebSocketUrl, + shouldActivateWebRuntime, + takeOverWebSession, + useWebConnection, +} from "./webBridge"; + +class FakeWebSocket { + static OPEN = 1; + static CLOSED = 3; + static instances: FakeWebSocket[] = []; + + readonly url: string; + readyState = FakeWebSocket.OPEN; + sent: unknown[] = []; + private listeners = new Map void>>(); + + constructor(url: string) { + this.url = url; + FakeWebSocket.instances.push(this); + queueMicrotask(() => this.emit("open", {})); + } + + addEventListener(type: string, fn: (ev: unknown) => void) { + let list = this.listeners.get(type); + if (!list) { + list = []; + this.listeners.set(type, list); + } + list.push(fn); + } + + send(data: string) { + this.sent.push(JSON.parse(data)); + } + + close() { + this.readyState = FakeWebSocket.CLOSED; + this.emit("close", {}); + } + + receive(msg: unknown) { + this.emit("message", { data: JSON.stringify(msg) }); + } + + private emit(type: string, ev: unknown) { + for (const fn of this.listeners.get(type) ?? []) fn(ev); + } +} + +describe("webBridge", () => { + const originalWs = globalThis.WebSocket; + + beforeEach(() => { + FakeWebSocket.instances = []; + document.head.innerHTML = ""; + sessionStorage.clear(); + delete (window as unknown as Record).__TAURI_INTERNALS__; + delete (window as unknown as Record).__TAURI_EVENT_PLUGIN_INTERNALS__; + useWebConnection.setState({ + active: false, + status: "idle", + windowLabel: "main", + serverHome: "", + serverOs: "linux", + }); + }); + + afterEach(() => { + globalThis.WebSocket = originalWs; + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it("resolves WebSocket URLs relative to direct and reverse-proxied page URLs", () => { + expect(resolveWebSocketUrl("http://localhost:8080/")).toBe("ws://localhost:8080/api/ws"); + expect(resolveWebSocketUrl("https://host.example/user/proj/r/session/abc/")).toBe( + "wss://host.example/user/proj/r/session/abc/api/ws", + ); + expect(resolveWebSocketUrl("https://host.example/ide/?project=/workspace#top")).toBe( + "wss://host.example/ide/api/ws", + ); + }); + + it("encodes Tauri Channel arguments into $channel objects", () => { + const fakeChannel = { __TAURI_TO_IPC_KEY__: () => "__CHANNEL__:42" }; + expect(encodeWebArgs({ path: "/tmp/a", onEvent: fakeChannel, nested: [fakeChannel] })).toEqual({ + path: "/tmp/a", + onEvent: { $channel: 42 }, + nested: [{ $channel: 42 }], + }); + }); + + it("activates only when the openidea-web meta tag is present and native Tauri is absent", () => { + expect(shouldActivateWebRuntime()).toBe(false); + const meta = document.createElement("meta"); + meta.name = "openidea-web"; + meta.content = "1"; + document.head.appendChild(meta); + expect(shouldActivateWebRuntime()).toBe(true); + + (window as unknown as Record).__TAURI_INTERNALS__ = {}; + expect(shouldActivateWebRuntime()).toBe(false); + }); + + it("installs Tauri internals over WebSocket, handles invoke, channels, events, and plugin shims", async () => { + const meta = document.createElement("meta"); + meta.name = "openidea-web"; + meta.content = "1"; + document.head.appendChild(meta); + + globalThis.WebSocket = FakeWebSocket as unknown as typeof WebSocket; + + const boot = initWebRuntime(); + await new Promise((r) => setTimeout(r, 0)); + const ws = FakeWebSocket.instances[0]!; + expect(ws.sent[0]).toEqual({ type: "hello", window: "main" }); + + ws.receive({ + type: "ready", + window: "main", + instance: "a", + server: { version: "0.1.38", protocol: 2, os: "linux", arch: "x86_64", home: "/home/dev" }, + }); + + await expect(boot).resolves.toBe(true); + expect(isWebMode()).toBe(true); + + const internals = ( + window as unknown as { + __TAURI_INTERNALS__: { + invoke: (cmd: string, args?: Record) => Promise; + transformCallback: (cb: (payload: unknown) => void, once?: boolean) => number; + }; + } + ).__TAURI_INTERNALS__; + + // Plugin shims work locally without hitting WebSocket. + await internals.invoke("plugin:window|set_title", { title: "My Project" }); + expect(document.title).toBe("My Project"); + await expect(internals.invoke("plugin:path|resolve_directory", { directory: 21 })).resolves.toBe("/home/dev"); + await expect(internals.invoke("plugin:window|get_all_windows")).resolves.toEqual(["main"]); + + // Command invoke + response. + const req = internals.invoke("app_info", {}) as Promise; + const sentInvoke = ws.sent[1] as { type: string; id: number; cmd: string }; + expect(sentInvoke.type).toBe("invoke"); + expect(sentInvoke.cmd).toBe("app_info"); + ws.receive({ type: "response", id: sentInvoke.id, ok: true, data: { version: "0.1.38" } }); + await expect(req).resolves.toEqual({ version: "0.1.38" }); + + // Channel streaming delivers ordered frames and cleans up on channelEnd. + const received: unknown[] = []; + const cbId = internals.transformCallback((msg: unknown) => received.push(msg)) as number; + const chObj = { __TAURI_TO_IPC_KEY__: () => `__CHANNEL__:${cbId}` }; + const streamReq = internals.invoke("terminal_spawn", { onOutput: chObj }) as Promise; + const sentStream = ws.sent[2] as { id: number; args: { onEvent?: unknown; onOutput: { $channel: number } } }; + expect(sentStream.args.onOutput).toEqual({ $channel: cbId }); + ws.receive({ type: "channel", id: cbId, data: "hello " }); + ws.receive({ type: "channel", id: cbId, data: "world" }); + ws.receive({ type: "response", id: sentStream.id, ok: true, data: 1 }); + await expect(streamReq).resolves.toBe(1); + ws.receive({ type: "channelEnd", id: cbId }); + // Further frames after channelEnd are ignored because the callback was unregistered. + ws.receive({ type: "channel", id: cbId, data: "late" }); + expect(received).toEqual([ + { index: 0, message: "hello " }, + { index: 1, message: "world" }, + { index: 2, end: true }, + ]); + + // Backend events reach ide://event listeners and unlisten removes the callback. + const events: unknown[] = []; + const evCb = internals.transformCallback((e: unknown) => events.push(e)) as number; + const eventId = (await internals.invoke("plugin:event|listen", { event: "ide://event", handler: evCb })) as number; + ws.receive({ type: "event", window: "main", event: { type: "settingsChanged", key: "appearance.theme" } }); + expect(events).toHaveLength(1); + expect((events[0] as { payload: unknown }).payload).toEqual({ type: "settingsChanged", key: "appearance.theme" }); + await internals.invoke("plugin:event|unlisten", { event: "ide://event", eventId }); + ws.receive({ type: "event", window: "main", event: { type: "settingsChanged", key: "appearance.theme" } }); + expect(events).toHaveLength(1); + + // Dropping the socket enters reconnecting state. + ws.close(); + expect(useWebConnection.getState().status).toBe("reconnecting"); + }); + + it("handles superseded without auto-reconnecting and reconnects on takeOverWebSession", async () => { + vi.useFakeTimers(); + + const meta = document.createElement("meta"); + meta.name = "openidea-web"; + meta.content = "1"; + document.head.appendChild(meta); + + globalThis.WebSocket = FakeWebSocket as unknown as typeof WebSocket; + + const boot = initWebRuntime(); + await Promise.resolve(); + const firstWs = FakeWebSocket.instances[0]!; + firstWs.receive({ + type: "ready", + window: "main", + instance: "a", + server: { version: "0.1.38", protocol: 2, os: "linux", arch: "x86_64", home: "/home/dev" }, + }); + await expect(boot).resolves.toBe(true); + expect(useWebConnection.getState().status).toBe("connected"); + + const internals = ( + window as unknown as { + __TAURI_INTERNALS__: { + invoke: (cmd: string, args?: Record) => Promise; + }; + } + ).__TAURI_INTERNALS__; + + const pendingCall = internals.invoke("app_info", {}); + firstWs.receive({ type: "superseded" }); + + await expect(pendingCall).rejects.toEqual({ + kind: "io", + message: "Session opened in another browser tab", + }); + expect(useWebConnection.getState().status).toBe("superseded"); + expect(firstWs.readyState).toBe(FakeWebSocket.CLOSED); + + // Must not schedule auto-reconnect after being superseded. + vi.advanceTimersByTime(10_000); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(useWebConnection.getState().status).toBe("superseded"); + + // Taking over opens a fresh WebSocket and returns to connected once ready arrives. + takeOverWebSession(); + expect(useWebConnection.getState().status).toBe("connecting"); + expect(FakeWebSocket.instances).toHaveLength(2); + + await Promise.resolve(); + const secondWs = FakeWebSocket.instances[1]!; + expect(secondWs.sent[0]).toEqual({ type: "hello", window: "main" }); + + secondWs.receive({ + type: "ready", + window: "main", + instance: "a", + server: { version: "0.1.38", protocol: 2, os: "linux", arch: "x86_64", home: "/home/dev" }, + }); + expect(useWebConnection.getState().status).toBe("connected"); + }); + + it("reloads the page when it reconnects to a restarted server", async () => { + vi.useFakeTimers(); + const meta = document.createElement("meta"); + meta.name = "openidea-web"; + meta.content = "1"; + document.head.appendChild(meta); + globalThis.WebSocket = FakeWebSocket as unknown as typeof WebSocket; + const reload = vi.fn(); + vi.spyOn(window, "location", "get").mockReturnValue({ ...window.location, reload } as Location); + const server = { version: "0.1.38", protocol: 2, os: "linux", arch: "x86_64", home: "/home/dev" }; + + const boot = initWebRuntime(); + await Promise.resolve(); + FakeWebSocket.instances[0]!.receive({ type: "ready", window: "main", instance: "a", server }); + await expect(boot).resolves.toBe(true); + + // The same server again: the page keeps its state. + FakeWebSocket.instances[0]!.close(); + vi.advanceTimersByTime(1_000); + FakeWebSocket.instances[1]!.receive({ type: "ready", window: "main", instance: "a", server }); + expect(reload).not.toHaveBeenCalled(); + expect(useWebConnection.getState().status).toBe("connected"); + + // A restarted server: its projects and runs are gone, so the page starts over. + FakeWebSocket.instances[1]!.close(); + vi.advanceTimersByTime(1_000); + FakeWebSocket.instances[2]!.receive({ type: "ready", window: "main", instance: "b", server }); + expect(reload).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/platform/webBridge.ts b/src/platform/webBridge.ts new file mode 100644 index 0000000000..ecacf30cd9 --- /dev/null +++ b/src/platform/webBridge.ts @@ -0,0 +1,544 @@ +/** + * Browser runtime bridge for `openidea-server --web`. + * + * When the page is served by `openidea-server --web` (indicated by ``), + * this module opens a WebSocket to `api/ws` (resolved relative to `window.location.href` so reverse-proxy + * subpaths work automatically) and installs a lightweight `window.__TAURI_INTERNALS__` shim backed by that + * WebSocket. All generated `commands.*`, streaming `Channel`s, and `onIdeEvent` subscriptions then run + * unmodified against the remote Rust `Host`. + */ +import { create } from "zustand"; + +export type WebConnectionStatus = "idle" | "connecting" | "connected" | "reconnecting" | "superseded"; + +interface WebConnectionState { + active: boolean; + status: WebConnectionStatus; + windowLabel: string; + serverHome: string; + serverOs: string; +} + +export const useWebConnection = create(() => ({ + active: false, + status: "idle", + windowLabel: "main", + serverHome: "", + serverOs: "linux", +})); + +/** True when this page is connected to `openidea-server --web` in a regular browser. */ +export function isWebMode(): boolean { + return useWebConnection.getState().active; +} + +let triggerTakeOver: (() => void) | null = null; + +/** Reconnects and reclaims this window session after another browser tab took over. */ +export function takeOverWebSession(): void { + if (!useWebConnection.getState().active || !triggerTakeOver) return; + triggerTakeOver(); +} + +const WINDOW_SESSION_KEY = "openidea.web.window"; +const SERIALIZE_TO_IPC_FN = "__TAURI_TO_IPC_KEY__"; +const CHANNEL_RE = /^__CHANNEL__:(\d+)$/; + +interface ReadyMessage { + type: "ready"; + window: string; + instance: string; + server: { + version: string; + protocol: number; + os: string; + arch: string; + home: string; + }; +} + +interface ResponseMessage { + type: "response"; + id: number; + ok: boolean; + data?: unknown; + error?: unknown; +} + +interface ChannelFrameMessage { + type: "channel"; + id: number; + data: unknown; +} + +interface ChannelEndFrameMessage { + type: "channelEnd"; + id: number; +} + +interface EventFrameMessage { + type: "event"; + window: string | null; + event: unknown; +} + +interface PongMessage { + type: "pong"; +} + +interface SupersededMessage { + type: "superseded"; +} + +type ServerMessage = + | ReadyMessage + | ResponseMessage + | ChannelFrameMessage + | ChannelEndFrameMessage + | EventFrameMessage + | PongMessage + | SupersededMessage; + +/** Resolves the WebSocket endpoint relative to `pageHref` (preserving any reverse-proxy subpath). */ +export function resolveWebSocketUrl(pageHref: string): string { + const url = new URL("api/ws", pageHref); + url.protocol = url.protocol === "https:" ? "wss:" : "ws:"; + url.hash = ""; + return url.toString(); +} + +/** Replaces Tauri `Channel` objects in command arguments with `{ $channel: id }` markers for the server. */ +export function encodeWebArgs(value: unknown, channels?: number[]): unknown { + if (value === null || value === undefined || typeof value !== "object") return value; + if (Array.isArray(value)) return value.map((item) => encodeWebArgs(item, channels)); + const record = value as Record; + if (typeof record[SERIALIZE_TO_IPC_FN] === "function") { + const serialized = (record[SERIALIZE_TO_IPC_FN] as () => unknown)(); + if (typeof serialized === "string") { + const m = CHANNEL_RE.exec(serialized); + if (m) { + const id = Number(m[1]); + channels?.push(id); + return { $channel: id }; + } + } + return serialized; + } + const out: Record = {}; + for (const [k, v] of Object.entries(record)) { + if (v !== undefined) out[k] = encodeWebArgs(v, channels); + } + return out; +} + +/** Detects whether the current page should boot the web server bridge. */ +export function shouldActivateWebRuntime(): boolean { + if (typeof window === "undefined" || typeof document === "undefined") return false; + if ("__TAURI_INTERNALS__" in window) return false; + if (document.querySelector('meta[name="openidea-web"]')?.getAttribute("content") === "1") return true; + if (import.meta.env.DEV && new URLSearchParams(window.location.search).has("openidea-web")) return true; + return false; +} + +function allocateWindowLabel(): string { + const params = new URLSearchParams(window.location.search); + const explicit = params.get("window")?.trim(); + if (explicit) { + try { + sessionStorage.setItem(WINDOW_SESSION_KEY, explicit); + } catch { + /* storage unavailable */ + } + return explicit; + } + try { + const saved = sessionStorage.getItem(WINDOW_SESSION_KEY); + if (saved) return saved; + } catch { + /* storage unavailable */ + } + const label = params.has("newWindow") ? `web-${Math.random().toString(36).slice(2, 10)}` : "main"; + try { + sessionStorage.setItem(WINDOW_SESSION_KEY, label); + } catch { + /* storage unavailable */ + } + return label; +} + +interface PendingCall { + resolve: (value: unknown) => void; + reject: (reason: unknown) => void; +} + +/** + * Connects to `openidea-server --web` and installs the `window.__TAURI_INTERNALS__` shim. + * Returns `false` when running in native Tauri desktop or standalone frontend dev/test mode. + */ +export async function initWebRuntime(): Promise { + if (!shouldActivateWebRuntime()) return false; + + const windowLabel = allocateWindowLabel(); + const requestedProject = new URLSearchParams(window.location.search).get("project"); + const wsUrl = resolveWebSocketUrl(window.location.href); + + let nextCallbackId = 1; + let nextEventId = 1; + let nextInvokeId = 1; + let serverHome = ""; + let serverInstance: string | null = null; + let ws: WebSocket | null = null; + let reconnectTimer: number | null = null; + let reconnectAttempt = 0; + + const callbacks = new Map void; once: boolean }>(); + const channelSeq = new Map(); + const activeChannels = new Set(); + const eventListeners = new Map>(); + const pending = new Map(); + + const removeEventListener = (event: string, eventId: number) => { + const map = eventListeners.get(event); + if (!map) return; + const callbackId = map.get(eventId); + map.delete(eventId); + if (map.size === 0) eventListeners.delete(event); + if (callbackId !== undefined) { + callbacks.delete(callbackId); + channelSeq.delete(callbackId); + } + }; + + const dispatchLocalEvent = (eventName: string, payload: unknown) => { + const listeners = eventListeners.get(eventName); + if (!listeners) return; + for (const [id, callbackId] of [...listeners.entries()]) { + const cb = callbacks.get(callbackId); + if (!cb) continue; + if (cb.once) removeEventListener(eventName, id); + try { + cb.fn({ event: eventName, id, payload }); + } catch (e) { + console.error(`Error in event listener for ${eventName}`, e); + } + } + }; + + const deliverChannel = (id: number, data: unknown) => { + const cb = callbacks.get(id); + if (!cb) return; + const index = channelSeq.get(id) ?? 0; + channelSeq.set(id, index + 1); + cb.fn({ index, message: data }); + }; + + const endChannel = (id: number) => { + activeChannels.delete(id); + const cb = callbacks.get(id); + const index = channelSeq.get(id) ?? 0; + if (cb) { + try { + cb.fn({ index, end: true }); + } catch { + /* ignore cleanup errors from listener */ + } + } + callbacks.delete(id); + channelSeq.delete(id); + }; + + const endAllActiveChannels = () => { + for (const id of [...activeChannels]) { + endChannel(id); + } + }; + + const rejectAllPending = (message: string) => { + for (const [id, call] of pending.entries()) { + pending.delete(id); + call.reject({ kind: "io", message }); + } + }; + + const handlePluginCommand = (cmd: string, args: Record): unknown => { + switch (cmd) { + case "plugin:event|listen": { + const event = String(args.event ?? ""); + const handler = Number(args.handler ?? 0); + const id = nextEventId++; + let map = eventListeners.get(event); + if (!map) { + map = new Map(); + eventListeners.set(event, map); + } + map.set(id, handler); + return id; + } + case "plugin:event|unlisten": { + const event = String(args.event ?? ""); + const eventId = Number(args.eventId ?? 0); + removeEventListener(event, eventId); + return null; + } + case "plugin:event|emit": + case "plugin:event|emit_to": { + const event = String(args.event ?? ""); + dispatchLocalEvent(event, args.payload); + return null; + } + case "plugin:window|set_title": { + if (typeof args.title === "string") document.title = args.title; + return null; + } + // One browser tab is one window with one webview. + case "plugin:window|get_all_windows": + return [windowLabel]; + case "plugin:webview|get_all_webviews": + return [{ windowLabel, label: windowLabel }]; + case "plugin:window|is_fullscreen": + return Boolean(document.fullscreenElement); + case "plugin:window|is_maximized": + return true; + case "plugin:window|is_minimized": + return false; + case "plugin:window|is_focused": + return document.hasFocus(); + case "plugin:window|is_visible": + return !document.hidden; + case "plugin:window|scale_factor": + return window.devicePixelRatio || 1; + case "plugin:window|inner_size": + case "plugin:window|outer_size": + return { width: window.innerWidth, height: window.innerHeight }; + case "plugin:window|inner_position": + case "plugin:window|outer_position": + return { x: 0, y: 0 }; + case "plugin:window|theme": + return window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light"; + case "plugin:window|set_focus": + window.focus(); + return null; + case "plugin:path|resolve_directory": { + const dir = Number(args.directory ?? 0); + // BaseDirectory.Home = 21 in @tauri-apps/api/path + if (dir === 21) return serverHome || "/"; + return serverHome || "/"; + } + case "plugin:path|join": { + const paths = Array.isArray(args.paths) ? args.paths.map(String) : []; + return paths.join("/").replace(/\/+/g, "/"); + } + default: + if (cmd.startsWith("plugin:window|") || cmd.startsWith("plugin:webview|")) return null; + return undefined; + } + }; + + const invoke = (cmd: string, rawArgs?: Record): Promise => { + const args = rawArgs ?? {}; + if (cmd.startsWith("plugin:")) { + const local = handlePluginCommand(cmd, args); + if (local !== undefined) return Promise.resolve(local); + } + const callChannels: number[] = []; + const encoded = encodeWebArgs(args, callChannels); + if (!ws || ws.readyState !== WebSocket.OPEN) { + for (const cid of callChannels) endChannel(cid); + return Promise.reject({ kind: "io", message: "Not connected to OpenIDEA server" }); + } + const id = nextInvokeId++; + for (const cid of callChannels) activeChannels.add(cid); + return new Promise((resolve, reject) => { + pending.set(id, { resolve, reject }); + try { + ws!.send(JSON.stringify({ type: "invoke", id, cmd, args: encoded })); + } catch (e) { + pending.delete(id); + for (const cid of callChannels) endChannel(cid); + reject({ kind: "io", message: e instanceof Error ? e.message : String(e) }); + } + }); + }; + + const internals = { + invoke, + transformCallback: (callback?: (payload: unknown) => void, once = false) => { + const id = nextCallbackId++; + if (callback) callbacks.set(id, { fn: callback, once }); + return id; + }, + unregisterCallback: (id: number) => { + activeChannels.delete(id); + callbacks.delete(id); + channelSeq.delete(id); + }, + convertFileSrc: (filePath: string) => filePath, + metadata: { + currentWindow: { label: windowLabel }, + currentWebview: { windowLabel, label: windowLabel }, + windows: [{ label: windowLabel }], + webviews: [{ windowLabel, label: windowLabel }], + }, + }; + + const eventInternals = { + unregisterListener: (event: string, eventId: number) => { + removeEventListener(event, eventId); + }, + }; + + Object.assign(window, { + __TAURI_INTERNALS__: internals, + __TAURI_EVENT_PLUGIN_INTERNALS__: eventInternals, + }); + + useWebConnection.setState({ active: true, status: "connecting", windowLabel }); + + const connect = (isInitial: boolean): Promise => + new Promise((resolveInitial, rejectInitial) => { + let settled = false; + let superseded = false; + const socket = new WebSocket(wsUrl); + ws = socket; + + const initialTimer = isInitial + ? window.setTimeout(() => { + if (!settled) { + settled = true; + socket.close(); + rejectInitial(new Error(`Timed out connecting to OpenIDEA server at ${wsUrl}`)); + } + }, 15_000) + : null; + + socket.addEventListener("open", () => { + socket.send( + JSON.stringify({ + type: "hello", + window: windowLabel, + ...(isInitial && requestedProject ? { project: requestedProject } : {}), + }), + ); + }); + + socket.addEventListener("message", (ev) => { + if (typeof ev.data !== "string") return; + let msg: ServerMessage; + try { + msg = JSON.parse(ev.data) as ServerMessage; + } catch { + return; + } + switch (msg.type) { + case "ready": { + // A restarted server has none of this page's projects, terminals or runs: start over. + // The unsaved-changes guard still asks before the page goes. + if (serverInstance !== null && serverInstance !== msg.instance) { + window.location.reload(); + return; + } + serverInstance = msg.instance; + serverHome = msg.server.home; + reconnectAttempt = 0; + useWebConnection.setState({ + active: true, + status: "connected", + windowLabel: msg.window, + serverHome: msg.server.home, + serverOs: msg.server.os, + }); + if (!settled) { + settled = true; + if (initialTimer !== null) window.clearTimeout(initialTimer); + resolveInitial(); + } + break; + } + case "response": { + const call = pending.get(msg.id); + if (!call) break; + pending.delete(msg.id); + if (msg.ok) call.resolve(msg.data ?? null); + else call.reject(msg.error ?? { kind: "internal", message: "Command failed" }); + break; + } + case "channel": { + deliverChannel(msg.id, msg.data); + break; + } + case "channelEnd": { + endChannel(msg.id); + break; + } + case "event": { + dispatchLocalEvent("ide://event", msg.event); + break; + } + case "pong": + break; + case "superseded": { + superseded = true; + if (ws === socket) ws = null; + if (reconnectTimer !== null) { + window.clearTimeout(reconnectTimer); + reconnectTimer = null; + } + rejectAllPending("Session opened in another browser tab"); + endAllActiveChannels(); + useWebConnection.setState({ status: "superseded" }); + socket.close(); + break; + } + } + }); + + socket.addEventListener("close", () => { + if (ws === socket) ws = null; + if (superseded) { + if (!settled) { + settled = true; + if (initialTimer !== null) window.clearTimeout(initialTimer); + rejectInitial(new Error("Session opened in another browser tab")); + } + return; + } + rejectAllPending("Connection to OpenIDEA server closed"); + endAllActiveChannels(); + if (!settled) { + settled = true; + if (initialTimer !== null) window.clearTimeout(initialTimer); + rejectInitial(new Error(`Could not connect to OpenIDEA server at ${wsUrl}`)); + return; + } + useWebConnection.setState({ status: "reconnecting" }); + const delay = Math.min(5_000, 500 * 2 ** reconnectAttempt); + reconnectAttempt += 1; + if (reconnectTimer !== null) window.clearTimeout(reconnectTimer); + reconnectTimer = window.setTimeout(() => { + reconnectTimer = null; + void connect(false).catch(() => {}); + }, delay); + }); + + socket.addEventListener("error", () => { + if (!settled) { + settled = true; + if (initialTimer !== null) window.clearTimeout(initialTimer); + rejectInitial(new Error(`WebSocket connection error for ${wsUrl}`)); + } + }); + }); + + triggerTakeOver = () => { + if (reconnectTimer !== null) { + window.clearTimeout(reconnectTimer); + reconnectTimer = null; + } + reconnectAttempt = 0; + useWebConnection.setState({ status: "connecting" }); + void connect(false).catch(() => {}); + }; + + await connect(true); + return true; +} diff --git a/src/windowBoot.tsx b/src/windowBoot.tsx index 56a8f1ea30..9549dfbbb7 100644 --- a/src/windowBoot.tsx +++ b/src/windowBoot.tsx @@ -11,6 +11,7 @@ import { guessOs } from "./platform/platformInfo"; import { installPointerFocus } from "./platform/pointerFocus"; import { installReorderedTapClick } from "./platform/reordered-tap-click"; import { hideSplash } from "./platform/splash"; +import { isWebMode } from "./platform/webBridge"; import { installMiddleClickPasteGuard, installWebKitClipboardGuard } from "./platform/webkitClipboard"; import { prefetchLazyComponents } from "./ui"; import { installFullscreenDragGuard, installWindowDrag, trackFullscreen } from "./workbench/window-drag"; @@ -33,7 +34,8 @@ export function activateList(what: string, list: ReadonlyArray { const os = guessOs(); document.documentElement.dataset.os = os; - if (import.meta.env.DEV && isTauri()) { + const desktop = isTauri() && !isWebMode(); + if (import.meta.env.DEV && desktop) { // The Tauri MCP bridge returns eval results via `window.__TAURI__` on Windows/Linux // (macOS evaluates natively). Dev only, so release builds keep withGlobalTauri off. const [{ invoke }, { emit }] = await Promise.all([import("@tauri-apps/api/core"), import("@tauri-apps/api/event")]); @@ -45,16 +47,18 @@ export async function installCommonWindowBoot(): Promise { // second press like the release before it, which the shim would take for a reordered tap and // click twice. if (os === "macos" && !/Chrome|Firefox/.test(navigator.userAgent)) installReorderedTapClick(); - if (os === "linux" && isTauri()) { + if (os === "linux" && desktop) { installWebKitClipboardGuard(); installMiddleClickPasteGuard(); } - // A double click on the title bar fills the work area; the backend steps the frame once per - // presented webview frame, because AppKit's own zoom hides the page until the resize ends. - installWindowDrag({ - toggleMaximize: () => call(commands.windowToggleZoom()).catch((e) => console.warn("cannot zoom the window", e)), - }); - if (os !== "macos" && isTauri()) installFullscreenDragGuard(trackFullscreen()); + if (desktop) { + // A double click on the title bar fills the work area; the backend steps the frame once per + // presented webview frame, because AppKit's own zoom hides the page until the resize ends. + installWindowDrag({ + toggleMaximize: () => call(commands.windowToggleZoom()).catch((e) => console.warn("cannot zoom the window", e)), + }); + } + if (os !== "macos" && desktop) installFullscreenDragGuard(trackFullscreen()); installPointerFocus(); installMiddleClickLinks(); installImeKeyGuard(); diff --git a/src/workbench/TitleBar.tsx b/src/workbench/TitleBar.tsx index d00db18197..412ade0e61 100644 --- a/src/workbench/TitleBar.tsx +++ b/src/workbench/TitleBar.tsx @@ -2,6 +2,7 @@ import { ContributedToolbar } from "./ContributedToolbar"; import { useMemo, useRef, useState } from "react"; import clsx from "clsx"; import { useActions } from "@/platform/actions"; +import { isWebMode } from "@/platform/webBridge"; import { shortcutLabel, useKeymap } from "@/platform/keymap"; import { basename, useProject } from "@/platform/project"; import { BarButton, Icon, IconButton, Menu, type MenuItem, showContextMenu, T } from "@/ui"; @@ -326,6 +327,7 @@ export function TitleBar({ }) { const overlay = usePlatform((s) => s.overlayTitleBar); const frameless = usePlatform((s) => s.framelessTitleBar); + const showMainMenu = frameless || isWebMode(); const windowButtons = usePlatform((s) => s.windowButtons); const { map, shown, menu } = useToolbar(); const [menuExpanded, setMenuExpanded] = useState(false); @@ -344,7 +346,7 @@ export function TitleBar({ frameless && captionButtons(windowButtons, "left", dialog).length > 0 && styles.captionsAtLeft, frameless && captionButtons(windowButtons, "right", dialog).length === 0 && styles.noCaptionsAtRight, ); - // Where the title bar carries the main menu (Windows, Linux) it stays, or nothing + // Where the title bar carries the main menu (Windows, Linux, web) it stays, or nothing // would lead back out of Distraction Free Mode or bring the toolbar back. if (bare || compact) return ( @@ -355,13 +357,13 @@ export function TitleBar({ data-titlebar={compact ? "compact" : "bare"} > {frameless && } - {frameless && } + {showMainMenu && } {compact ? : frameless &&
} {frameless && } ); const entry = (id: string) => ; - const menuRow = frameless && !minimal && separateMenu; + const menuRow = showMainMenu && !minimal && separateMenu; const header = (
{frameless && } - {frameless && !minimal && !separateMenu && } + {showMainMenu && !minimal && !separateMenu && } {title && ( {typeof title === "string" ? {title} : title} diff --git a/src/workbench/WebConnectionBanner.module.css b/src/workbench/WebConnectionBanner.module.css new file mode 100644 index 0000000000..9c6e183cfa --- /dev/null +++ b/src/workbench/WebConnectionBanner.module.css @@ -0,0 +1,38 @@ +.banner { + display: flex; + align-items: center; + gap: var(--space-2); + padding: var(--space-1-5) var(--space-3); + background: var(--bg-feedback-warning); + border-bottom: 1px solid var(--border-feedback-warning); + color: var(--fg); + font-size: var(--fs-small); +} + +.icon { + color: var(--warning); + flex-shrink: 0; +} + +.action { + margin-inline-start: auto; + padding: var(--space-0-5) var(--space-2); + border: 1px solid var(--border-button); + border-radius: var(--radius-control); + background: var(--bg-control); + color: var(--fg-strong); + font-size: var(--fs-small); + line-height: 1.4; + cursor: pointer; + flex-shrink: 0; + transition: background var(--dur-fast) var(--ease); +} + +.action:hover { + background: var(--bg-control-hover); +} + +.action:focus-visible { + outline: 2px solid var(--focus-ring); + outline-offset: 1px; +} diff --git a/src/workbench/WebConnectionBanner.test.tsx b/src/workbench/WebConnectionBanner.test.tsx new file mode 100644 index 0000000000..4c79cef36a --- /dev/null +++ b/src/workbench/WebConnectionBanner.test.tsx @@ -0,0 +1,47 @@ +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import * as webBridge from "@/platform/webBridge"; +import { useWebConnection } from "@/platform/webBridge"; +import { WebConnectionBanner } from "./WebConnectionBanner"; + +describe("WebConnectionBanner", () => { + afterEach(() => { + vi.restoreAllMocks(); + useWebConnection.setState({ + active: false, + status: "idle", + windowLabel: "main", + serverHome: "", + serverOs: "linux", + }); + }); + + it("renders nothing outside web mode or while connected", () => { + const { container } = render(); + expect(container.firstChild).toBeNull(); + + act(() => useWebConnection.setState({ active: true, status: "connected" })); + expect(container.firstChild).toBeNull(); + }); + + it("shows a reconnecting status banner while the web socket is reconnecting", () => { + act(() => useWebConnection.setState({ active: true, status: "reconnecting" })); + render(); + const banner = screen.getByRole("status"); + expect(banner.hasAttribute("data-web-reconnecting")).toBe(true); + expect(banner.textContent).toContain("Reconnecting"); + }); + + it("shows a superseded status banner with a Take Over button", () => { + const takeOverSpy = vi.spyOn(webBridge, "takeOverWebSession").mockImplementation(() => {}); + act(() => useWebConnection.setState({ active: true, status: "superseded" })); + render(); + + const banner = screen.getByRole("status"); + expect(banner.hasAttribute("data-web-superseded")).toBe(true); + expect(banner.textContent).toContain("This OpenIDEA session is open in another browser tab."); + + fireEvent.click(screen.getByRole("button", { name: "Take Over" })); + expect(takeOverSpy).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/workbench/WebConnectionBanner.tsx b/src/workbench/WebConnectionBanner.tsx new file mode 100644 index 0000000000..70611b7f56 --- /dev/null +++ b/src/workbench/WebConnectionBanner.tsx @@ -0,0 +1,31 @@ +import { takeOverWebSession, useWebConnection } from "@/platform/webBridge"; +import { Icon, T } from "@/ui"; +import styles from "./WebConnectionBanner.module.css"; + +/** Non-intrusive banner shown in browser mode while reconnecting or superseded by another tab. */ +export function WebConnectionBanner() { + const active = useWebConnection((s) => s.active); + const status = useWebConnection((s) => s.status); + if (!active || (status !== "reconnecting" && status !== "superseded")) return null; + if (status === "superseded") { + return ( +
+ + + This OpenIDEA session is open in another browser tab. + + +
+ ); + } + return ( +
+ + + Connection to OpenIDEA server lost. Reconnecting… + +
+ ); +} diff --git a/src/workbench/activate.ts b/src/workbench/activate.ts index feeacf3fb3..46f1fc5e8b 100644 --- a/src/workbench/activate.ts +++ b/src/workbench/activate.ts @@ -12,6 +12,7 @@ import { registerOverlay, registerStatusItem, registerToolWindow, + registerWorkbenchBanner, } from "./contributions"; import { installBrowserGuards } from "./browserGuards"; import { installDistractionFree } from "./distractionFree"; @@ -34,6 +35,8 @@ import { toolWindowServiceImpl, } from "./toolwindows/store"; import { TabColorPicker } from "./TabColorPicker"; +import { WebConnectionBanner } from "./WebConnectionBanner"; +import { installWebSessionGuard } from "./webSessionGuard"; export function activateWorkbench(): () => void { provideToolWindowService(toolWindowServiceImpl); @@ -81,7 +84,9 @@ export function activateWorkbench(): () => void { installTaskEvents(), installNotifyEvents(), installBrowserGuards(), + installWebSessionGuard(), installFileDrop(), + registerWorkbenchBanner({ id: "workbench.webConnection", component: WebConnectionBanner }), registerOverlay({ id: "workbench.customizeToolbar", component: MainToolbarDialogHost }), registerOverlay({ id: "workbench.backgroundTasks", component: BackgroundTasksHost }), registerOverlay({ id: "workbench.projectColor", component: TabColorPicker }), diff --git a/src/workbench/webSessionGuard.test.ts b/src/workbench/webSessionGuard.test.ts new file mode 100644 index 0000000000..391636c813 --- /dev/null +++ b/src/workbench/webSessionGuard.test.ts @@ -0,0 +1,92 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { useWebConnection } from "@/platform/webBridge"; +import * as contributions from "./contributions"; +import { installWebSessionGuard } from "./webSessionGuard"; + +function fireBeforeUnload() { + const event = new Event("beforeunload", { cancelable: true }) as BeforeUnloadEvent; + window.dispatchEvent(event); + return event; +} + +describe("webSessionGuard", () => { + let dispose: () => void; + + beforeEach(() => { + useWebConnection.setState({ + active: false, + status: "idle", + windowLabel: "main", + serverHome: "", + serverOs: "linux", + }); + dispose = installWebSessionGuard(); + }); + + afterEach(() => { + dispose(); + vi.restoreAllMocks(); + useWebConnection.setState({ + active: false, + status: "idle", + windowLabel: "main", + serverHome: "", + serverOs: "linux", + }); + }); + + it("is inactive outside web mode even when documents are dirty", () => { + vi.spyOn(contributions, "maybeEditorService").mockReturnValue({ + dirtyDocumentIds: () => [1], + untitledDirtyDocumentIds: () => [2], + } as unknown as contributions.EditorService); + + const event = fireBeforeUnload(); + expect(event.defaultPrevented).toBe(false); + }); + + it("does not prevent unload in web mode when all documents are clean", () => { + useWebConnection.setState({ active: true, status: "connected" }); + vi.spyOn(contributions, "maybeEditorService").mockReturnValue({ + dirtyDocumentIds: () => [], + untitledDirtyDocumentIds: () => [], + } as unknown as contributions.EditorService); + + const event = fireBeforeUnload(); + expect(event.defaultPrevented).toBe(false); + }); + + it("prevents unload in web mode when dirtyDocumentIds is non-empty", () => { + useWebConnection.setState({ active: true, status: "connected" }); + vi.spyOn(contributions, "maybeEditorService").mockReturnValue({ + dirtyDocumentIds: () => [42], + untitledDirtyDocumentIds: () => [], + } as unknown as contributions.EditorService); + + const event = fireBeforeUnload(); + expect(event.defaultPrevented).toBe(true); + }); + + it("prevents unload in web mode when untitledDirtyDocumentIds is non-empty", () => { + useWebConnection.setState({ active: true, status: "connected" }); + vi.spyOn(contributions, "maybeEditorService").mockReturnValue({ + dirtyDocumentIds: () => [], + untitledDirtyDocumentIds: () => [7], + } as unknown as contributions.EditorService); + + const event = fireBeforeUnload(); + expect(event.defaultPrevented).toBe(true); + }); + + it("removes the beforeunload listener on dispose", () => { + useWebConnection.setState({ active: true, status: "connected" }); + vi.spyOn(contributions, "maybeEditorService").mockReturnValue({ + dirtyDocumentIds: () => [1], + untitledDirtyDocumentIds: () => [], + } as unknown as contributions.EditorService); + + dispose(); + const event = fireBeforeUnload(); + expect(event.defaultPrevented).toBe(false); + }); +}); diff --git a/src/workbench/webSessionGuard.ts b/src/workbench/webSessionGuard.ts new file mode 100644 index 0000000000..d607fe5918 --- /dev/null +++ b/src/workbench/webSessionGuard.ts @@ -0,0 +1,19 @@ +/** + * Prompts before closing or navigating away from the browser tab in web mode + * when any open editor document has unsaved changes. + */ +import { isWebMode } from "@/platform/webBridge"; +import { maybeEditorService } from "./contributions"; + +export function installWebSessionGuard(): () => void { + const onBeforeUnload = (e: BeforeUnloadEvent) => { + if (!isWebMode()) return; + const editor = maybeEditorService(); + if ((editor?.dirtyDocumentIds?.().length ?? 0) > 0 || (editor?.untitledDirtyDocumentIds?.().length ?? 0) > 0) { + e.preventDefault(); + e.returnValue = ""; + } + }; + window.addEventListener("beforeunload", onBeforeUnload); + return () => window.removeEventListener("beforeunload", onBeforeUnload); +} diff --git a/vite.config.ts b/vite.config.ts index a2bd05f930..c431bc9519 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -5,8 +5,11 @@ import { fileURLToPath } from "node:url"; import process from "node:process"; const host = process.env.TAURI_DEV_HOST; +const webServer = process.env.OPENIDEA_WEB_SERVER; export default defineConfig(() => ({ + // Relative asset URLs keep both desktop bundles and reverse-proxied web deployments subpath-agnostic. + base: "./", plugins: [react()], resolve: { alias: [ @@ -25,6 +28,16 @@ export default defineConfig(() => ({ strictPort: true, host: host || false, hmr: host ? { protocol: "ws", host } : undefined, + ...(webServer + ? { + proxy: { + "/api": { + target: webServer, + ws: true, + }, + }, + } + : {}), watch: { ignored: [ "**/src-tauri/**",