diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 6207bb1a..cd1940ea 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -884,6 +884,7 @@ dependencies = [ "lithe-plugin-model", "lithe-protocol", "lithe-remote", + "lithe-terminal", "lithe-workspace", "quick-xml", "regex", @@ -1493,6 +1494,8 @@ dependencies = [ name = "lithe-terminal" version = "0.1.0" dependencies = [ + "base64", + "encoding_rs", "lithe-protocol", "serde", "serde_json", diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index c531738a..e7c91fa8 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -265,16 +265,21 @@ target. At most 256 texts of 4096 bytes. See `rust/fixtures/terminal/link-target ## Output styles -`outputStyle.decode` accepts `{text, state?}` and returns `{lines: Line[], state}`. A host sends each chunk of one -console's output as it arrives, passing back the `state` the previous answer returned (none for the first chunk), and -keeps only plain text plus styled ranges, so copying, search, output links and the IDE API never see an escape. A +`outputStyle.decode` accepts `{text, state?}` or `{bytes, encoding?, state?}` and returns `{lines: Line[], open: Line, +state}`. A host sends each chunk of one console's output as it arrives, passing back the `state` the previous answer +returned (none for the first chunk), and keeps only plain text plus styled ranges, so copying, search, output links +and the IDE API never see an escape. A host that reads a process's pipes sends `bytes`, the bytes exactly as written in +standard base64, so Core decides the characters (see Output encodings); `text` is for output that is already text, and +every chunk of one console uses the same kind. A `Line` is `{text, spans?}`: the text without its line ending and `{start, length, style}` ranges in UTF-16 code units, ascending and non-overlapping; text outside every range is plain. A `style` has optional `foreground` and `background` (`{index: 0-255}` or `{rgb: "#rrggbb"}`) and the flags `bold`, `dim`, `italic`, `underline`, `inverse`, `hidden` and `strikethrough`, each omitted when unset. `lines` are the lines the chunk ended, oldest first, the first continuing the -previous open line; `state.line` is the line still open, which the host shows after them. The rest of the state (the -style in effect, an unfinished escape sequence and a pending carriage return) is opaque to the host, and a state Core -did not return is `invalid_request`. +previous open line; `open` is the line still open, which the host shows after them. The state (the open line, the +style in effect, an unfinished escape sequence, a pending carriage return and, for bytes, the bytes of the open line +not decoded yet) is opaque to the host, and a state Core did not return, or returned for the other kind of input, is +`invalid_request`. A request with neither or both of `text` and `bytes`, or with `encoding` and `text`, is +`invalid_request`. SGR (`ESC [ … m`) sets the style across chunks and lines: 0 resets; 1, 2, 3, 4 (`4:0` off), 7, 8, 9 and 21 set attributes and 22–29 clear them; 30–37, 90–97, 40–47 and 100–107 pick palette colours 0–15, and 39 and 49 restore the @@ -289,6 +294,35 @@ draws `hidden` text in the background colour. A chunk is at most 1 MiB; lines lo line, and a line keeps at most 512 ranges. Lives in `rust/crates/terminal`; see `rust/fixtures/terminal/output-style-v1.json`. +## Output encodings + +A process writes bytes, and not always UTF-8: on Windows a program writing to a pipe often uses the system ANSI code +page (a JVM on a Chinese system writes GBK), and one build can mix both. For `bytes`, Core cuts the output into lines +at `\n` and `\r` before decoding, which is safe because every supported encoding is ASCII-compatible and none uses +those bytes or ESC inside a character (so UTF-16 is not supported), and decodes each line with the first candidate it +is valid in; a line valid in none is decoded with the candidate that replaces the fewest characters, the earlier on a +tie. An unfinished line is held as bytes until it ends, because its encoding is known only then, and `open` shows it +decoded so far (a character still incomplete is left out), so a later answer may show the same open line differently; +a held line that would outgrow the 16 KiB line limit is decoded up to its last character boundary instead. A chunk is +at most 1 MiB of bytes. + +`encoding` is a policy `{setting?, declared?, windows?}`. `setting` is `auto` (the default) or the id of the one +encoding every line is decoded with. In `auto`, the candidates are, in order and without repeats: `declared`, an +explicit encoding the starter of the process says it writes; `utf-8`; and, only when `windows` is true, `gbk`. +The default is UTF-8 everywhere, with GBK compatibility on Windows regardless of the host's locale or ANSI code page. +Hosts pass whether they are Windows; an absent policy is UTF-8 alone. A valid UTF-8 line stays UTF-8 when there is no +explicit declaration, and only lines that fail UTF-8 are tried as GBK on Windows. A single line mixing encodings or +legacy bytes that also happen to be valid UTF-8 cannot be unambiguously detected; explicit choices resolve ambiguity. +The ids are `utf-8`, `gbk`, `gb18030`, `big5`, `shift-jis`, `euc-jp`, `euc-kr`, `windows-874`, `windows-1250` to +`windows-1258` and `koi8-r`; parsing is case-insensitive and accepts the aliases `utf8`, `cp936`, `cp950`, `shift_jis`, +`sjis`, `cp932`, `eucjp`, `euckr`, `cp949`, `cp874`, `cp1250` to `cp1258`, `iso-8859-1`, `latin1` (both Windows-1252, +as in the WHATWG Encoding Standard) and `koi8r`. An unsupported id or unknown policy member is `invalid_request`. + +`outputEncoding.resolve` takes the same policy and returns `{candidates, encodings}`: the ids a line is tried in, in +order, and every id a setting may choose, in menu order, so a settings page can show what automatic means on this +machine. It fails as `outputStyle.decode` does for an unsupported id or an unknown member. See +`rust/fixtures/terminal/output-encoding-v1.json`. + The Rust core is the shared application runtime for macOS SwiftUI and Windows React/Tauri. macOS calls the stable C ABI while the Tauri host links the Rust crate directly. The C ABI remains: @@ -634,7 +668,8 @@ or removing a command fails until the table changes in the same commit. | `workbench.chromeLayout.reduce` | Apply one transition to the rearrangeable workbench chrome: stripe, title bar and status bar button placement, hidden stripe buttons and open tool panels (from `lithe-core-rules`) | | `workbench.notifications.reduceReadState` | Apply one notification arrival or mark a window's history read; return bounded unread identities and the ready-to-render count (from `lithe-core-rules`) | | `terminal.parseLinkTarget` | Resolve terminal link candidates into file or external targets | -| `outputStyle.decode` | Decode one chunk of console output with ANSI escapes into plain lines and styled ranges, carrying the console's state to the next chunk | +| `outputStyle.decode` | Decode one chunk of console output with ANSI escapes into plain lines and styled ranges, carrying the console's state to the next chunk; bytes are decoded line by line with the encoding each line is valid in | +| `outputEncoding.resolve` | List the encodings an output encoding policy tries, in order, and every encoding a setting may choose | | `debug.createSession` | Create a transport-neutral DAP session and return its initialize frame | | `debug.launch` | Queue a launch or attach request, including during initialization | | `debug.steppingFilters` | Return adapter defaults or normalize portable stepping filters | diff --git a/rust/crates/build/Cargo.toml b/rust/crates/build/Cargo.toml index a35df12a..b2e1111d 100644 --- a/rust/crates/build/Cargo.toml +++ b/rust/crates/build/Cargo.toml @@ -12,6 +12,7 @@ lithe-execution = { path = "../execution" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } lithe-remote = { path = "../remote", default-features = false, features = ["client"] } +lithe-terminal = { path = "../terminal" } lithe-workspace = { path = "../workspace" } quick-xml = "0.37" regex = "1.11" diff --git a/rust/crates/build/src/run_preparation.rs b/rust/crates/build/src/run_preparation.rs index 30efc2e6..054e8fd7 100644 --- a/rust/crates/build/src/run_preparation.rs +++ b/rust/crates/build/src/run_preparation.rs @@ -323,9 +323,26 @@ pub(crate) fn decode( } let mut fields = process_fields(request)?; fields["executable"] = json!({"kind":kind,"value":name}); + if let Some(encoding) = output_encoding(value).map_err(|()| invalid())? { + fields["outputEncoding"] = json!(encoding); + } Ok(fields) } +/// The encoding a process plan says the process writes to its output, as its stable id: the +/// host's automatic decoding tries it first (see `outputEncoding.resolve`). Absent is `None`; +/// a value that is not a supported id or alias is `Err`. +pub(super) fn output_encoding(process: &Value) -> Result, ()> { + match process.get("outputEncoding") { + None => Ok(None), + Some(value) => value + .as_str() + .and_then(|text| lithe_terminal::OutputEncoding::parse(text).ok()) + .map(|encoding| Some(encoding.id())) + .ok_or(()), + } +} + /// Common bounded arguments, environment and workspace-contained directory. pub(super) fn process_fields(request: &DecodeRunPreparationRequest) -> Validation { let invalid = || decode::invalid_output("Invalid provider process preparation result."); diff --git a/rust/crates/build/src/run_start.rs b/rust/crates/build/src/run_start.rs index 13b1c8a2..d1f5ef8a 100644 --- a/rust/crates/build/src/run_start.rs +++ b/rust/crates/build/src/run_start.rs @@ -7,7 +7,8 @@ use super::decode; use super::run_preparation::{ - process_fields, valid_configuration_type, DecodeRunPreparationRequest, MAX_ARGUMENT_BYTES, + output_encoding, process_fields, valid_configuration_type, DecodeRunPreparationRequest, + MAX_ARGUMENT_BYTES, }; use super::BuildManifest; use lithe_plugin_model::is_function_id; @@ -107,13 +108,28 @@ fn decode_start(payload: &DecodeStartPayload, required_tools: &[String]) -> Vali payload.temporary_directory.as_deref(), )?; for key in params.process.keys() { - if !["executable", "arguments", "workingDirectory", "environment"].contains(&key.as_str()) { + if ![ + "executable", + "arguments", + "workingDirectory", + "environment", + "outputEncoding", + ] + .contains(&key.as_str()) + { return Err(invalid( &format!("process.{key}"), "The process has no such field.", )); } } + let output_encoding = + output_encoding(&Value::Object(params.process.clone())).map_err(|()| { + invalid( + "process.outputEncoding", + "The output encoding is not a supported encoding.", + ) + })?; let fields = process_fields(&DecodeRunPreparationRequest { workspace_root: payload.workspace_root.clone(), root: ".".to_string(), @@ -168,6 +184,9 @@ fn decode_start(payload: &DecodeStartPayload, required_tools: &[String]) -> Vali }) .collect::>(), }); + if let Some(encoding) = output_encoding { + start["outputEncoding"] = json!(encoding); + } if let Some(debug) = ¶ms.debug { start["debug"] = start_debug(debug)?; } diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 3de8115b..c1462693 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -154,6 +154,10 @@ pub enum CoreCommand { /// Decodes one chunk of console output with ANSI escapes into plain lines and styled ranges /// (`outputStyle.decode`), from `lithe-terminal`. OutputStyleDecode, + /// Lists the character encodings console output may be decoded with, and the ones a + /// setting, a declaration and a code page select (`outputEncoding.resolve`), from + /// `lithe-terminal`. + OutputEncodingResolve, /// Language server sessions, documents, edits, requests and events (`lsp.*`). Lsp(LspCommand), /// Normalizes the stored proxy settings into the policy a network stack @@ -1358,6 +1362,7 @@ impl CoreCommand { } "terminal.parseLinkTarget" => Some(Self::TerminalParseLinkTarget), "outputStyle.decode" => Some(Self::OutputStyleDecode), + "outputEncoding.resolve" => Some(Self::OutputEncodingResolve), "debug.createSession" => Some(Self::Debug(DebugCommand::CreateSession)), "debug.launch" => Some(Self::Debug(DebugCommand::Launch)), "debug.steppingFilters" => Some(Self::Debug(DebugCommand::SteppingFilters)), @@ -1860,6 +1865,7 @@ mod tests { "outputLinks.match", "outputLinks.decodeResolution", "outputStyle.decode", + "outputEncoding.resolve", ] { assert!(CoreCommand::parse(command).is_some(), "missing {command}"); } diff --git a/rust/crates/core/src/runtime/dispatcher.rs b/rust/crates/core/src/runtime/dispatcher.rs index 4cfc9c3a..d91df0c0 100644 --- a/rust/crates/core/src/runtime/dispatcher.rs +++ b/rust/crates/core/src/runtime/dispatcher.rs @@ -501,6 +501,22 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon Err(error) => CoreResponse::failure(id, error), } } + CoreCommand::OutputEncodingResolve => { + let result = + serde_json::from_value::(parsed.payload) + .map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid output encoding request") + .with_details(error.to_string()) + }) + .and_then(lithe_terminal::resolve_output_encoding); + match result { + Ok(data) => CoreResponse::success( + id, + serde_json::to_value(data).expect("output encoding result should encode"), + ), + Err(error) => CoreResponse::failure(id, error), + } + } CoreCommand::MarkdownRender => { match serde_json::from_value::(parsed.payload).map_err(|error| { CoreError::new(ErrorCode::InvalidRequest, "Invalid Markdown render request") diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index 5c68cbd3..d8210850 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -2803,7 +2803,15 @@ fn provider_run_preparation_selects_targets_and_validates_launch_data() { let valid = decode(fixture["result"].clone()); assert_eq!(valid["status"], "ok", "{valid}"); assert_eq!(valid["launch"], fixture["result"]); + // A declared output encoding reaches the host as its stable id. + let mut declared = fixture["result"].clone(); + declared["outputEncoding"] = json!("Shift_JIS"); + let declared = decode(declared); + assert_eq!(declared["status"], "ok", "{declared}"); + assert_eq!(declared["launch"]["outputEncoding"], "shift-jis"); for (field, value) in [ + ("outputEncoding", json!("utf-16")), + ("outputEncoding", json!(936)), ("executable", json!({"kind":"command","value":"/bin/java"})), ("executable", json!({"kind":"absolute","value":"java"})), ("arguments", json!(["bad\u{0}"])), diff --git a/rust/crates/core/src/tests/protocol.rs b/rust/crates/core/src/tests/protocol.rs index c88e1c24..bab6f17f 100644 --- a/rust/crates/core/src/tests/protocol.rs +++ b/rust/crates/core/src/tests/protocol.rs @@ -584,12 +584,71 @@ fn output_style_fixtures_cross_the_json_boundary() { assert_eq!(result["ok"], true, "{}: {result}", case["name"]); lines.extend(result["data"]["lines"].as_array().unwrap().iter().cloned()); state = result["data"]["state"].clone(); + // For text the open line is the state's line. + assert_eq!(result["data"]["open"], state["line"], "{}", case["name"]); } assert_eq!(Value::Array(lines), case["lines"], "{}", case["name"]); assert_eq!(state["line"], case["open"], "{}", case["name"]); } } +#[test] +fn output_encoding_fixtures_cross_the_json_boundary() { + // Each decode case replays its byte chunks with the state the previous answer returned. + let fixture: Value = serde_json::from_str(include_str!( + "../../../../fixtures/terminal/output-encoding-v1.json" + )) + .unwrap(); + for case in fixture["decode"].as_array().unwrap() { + let mut lines = Vec::new(); + let mut state = Value::Null; + let mut open = Value::Null; + for chunk in case["chunks"].as_array().unwrap() { + let bytes = hex_bytes(chunk.as_str().unwrap()); + let mut request = serde_json::json!({ "bytes": BASE64.encode(bytes) }); + if !case["encoding"].is_null() { + request["encoding"] = case["encoding"].clone(); + } + if !state.is_null() { + request["state"] = state; + } + let result = call_fixture_command("outputStyle.decode", request); + assert_eq!(result["ok"], true, "{}: {result}", case["name"]); + lines.extend(result["data"]["lines"].as_array().unwrap().iter().cloned()); + open = result["data"]["open"].clone(); + state = result["data"]["state"].clone(); + } + assert_eq!(Value::Array(lines), case["lines"], "{}", case["name"]); + assert_eq!(open, case["open"], "{}", case["name"]); + } + for case in fixture["resolve"].as_array().unwrap() { + let result = call_fixture_command("outputEncoding.resolve", case["policy"].clone()); + if case["error"].is_null() { + assert_eq!(result["ok"], true, "{}: {result}", case["name"]); + assert_eq!( + result["data"]["candidates"], case["candidates"], + "{}", + case["name"] + ); + assert_eq!( + result["data"]["encodings"], fixture["encodings"], + "{}", + case["name"] + ); + } else { + assert_eq!(result["ok"], false, "{}: {result}", case["name"]); + assert_eq!(result["error"]["code"], case["error"], "{}", case["name"]); + } + } +} + +fn hex_bytes(hex: &str) -> Vec { + (0..hex.len()) + .step_by(2) + .map(|at| u8::from_str_radix(&hex[at..at + 2], 16).unwrap()) + .collect() +} + #[test] fn output_style_rejects_a_state_it_did_not_return() { let result = call_fixture_command( diff --git a/rust/crates/terminal/Cargo.toml b/rust/crates/terminal/Cargo.toml index b8528e02..b6b9dad0 100644 --- a/rust/crates/terminal/Cargo.toml +++ b/rust/crates/terminal/Cargo.toml @@ -3,9 +3,11 @@ name = "lithe-terminal" version = "0.1.0" edition = "2021" license = "Apache-2.0" -description = "Terminal output link detection and ANSI style decoding shared by every Lithe host" +description = "Terminal output link detection, output character decoding and ANSI style decoding shared by every Lithe host" [dependencies] +base64 = "0.22" +encoding_rs = "0.8" lithe-protocol = { path = "../protocol" } serde = { version = "1.0", features = ["derive"] } diff --git a/rust/crates/terminal/src/encoding.rs b/rust/crates/terminal/src/encoding.rs new file mode 100644 index 00000000..8c166bfb --- /dev/null +++ b/rust/crates/terminal/src/encoding.rs @@ -0,0 +1,427 @@ +//! Character encodings of console output, and which one decodes each line. +//! +//! A process writes bytes. Most write UTF-8, but a Windows program that writes to a pipe often +//! uses the system ANSI code page instead (a JVM on a Chinese system writes GBK there), and one +//! build can print both: a tool's own lines and the lines of a process it starts may differ. +//! Core therefore decides per line. A line that is valid UTF-8 is UTF-8, because text in a legacy +//! encoding is almost never valid UTF-8 by accident; otherwise the next candidate in which the +//! line is valid decodes it. The candidates come from an [`OutputEncodingPolicy`]: the user's +//! fixed choice alone, or, automatically, the encoding the starter of the process declared, +//! UTF-8, and GBK on Windows. The platform is explicit data, independent of the system locale. +//! +//! Every encoding here is ASCII-compatible, and in none of them does a byte of a multibyte +//! character equal `\n`, `\r` or ESC, so lines and escape sequences can be found in the bytes +//! before the characters are decoded. That rules out UTF-16, which file encodings support. +//! Codec tables come from `encoding_rs` (WHATWG Encoding Standard). + +use encoding_rs::{ + CoderResult, DecoderResult, Encoding, BIG5, EUC_JP, EUC_KR, GB18030, GBK, KOI8_R, SHIFT_JIS, + UTF_8, WINDOWS_1250, WINDOWS_1251, WINDOWS_1252, WINDOWS_1253, WINDOWS_1254, WINDOWS_1255, + WINDOWS_1256, WINDOWS_1257, WINDOWS_1258, WINDOWS_874, +}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; + +/// An encoding console output can be decoded with, identified by a stable string id. The ids +/// are the same as the file encoding ids for the encodings both support. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OutputEncoding { + /// UTF-8 (`utf-8`). + Utf8, + /// Simplified Chinese GBK (`gbk`). + Gbk, + /// Simplified Chinese GB 18030 (`gb18030`). + Gb18030, + /// Traditional Chinese Big5 (`big5`). + Big5, + /// Japanese Shift_JIS (`shift-jis`). + ShiftJis, + /// Japanese EUC-JP (`euc-jp`). + EucJp, + /// Korean EUC-KR (`euc-kr`). + EucKr, + /// Thai (`windows-874`). + Windows874, + /// Central European (`windows-1250`). + Windows1250, + /// Cyrillic (`windows-1251`). + Windows1251, + /// Western European (`windows-1252`). + Windows1252, + /// Greek (`windows-1253`). + Windows1253, + /// Turkish (`windows-1254`). + Windows1254, + /// Hebrew (`windows-1255`). + Windows1255, + /// Arabic (`windows-1256`). + Windows1256, + /// Baltic (`windows-1257`). + Windows1257, + /// Vietnamese (`windows-1258`). + Windows1258, + /// Russian KOI8-R (`koi8-r`). + Koi8R, +} + +/// Every output encoding, in the order a menu lists them. +pub const OUTPUT_ENCODINGS: [OutputEncoding; 18] = [ + OutputEncoding::Utf8, + OutputEncoding::Gbk, + OutputEncoding::Gb18030, + OutputEncoding::Big5, + OutputEncoding::ShiftJis, + OutputEncoding::EucJp, + OutputEncoding::EucKr, + OutputEncoding::Windows874, + OutputEncoding::Windows1250, + OutputEncoding::Windows1251, + OutputEncoding::Windows1252, + OutputEncoding::Windows1253, + OutputEncoding::Windows1254, + OutputEncoding::Windows1255, + OutputEncoding::Windows1256, + OutputEncoding::Windows1257, + OutputEncoding::Windows1258, + OutputEncoding::Koi8R, +]; + +impl OutputEncoding { + /// Stable identifier exchanged with hosts and plugins. + pub fn id(self) -> &'static str { + match self { + Self::Utf8 => "utf-8", + Self::Gbk => "gbk", + Self::Gb18030 => "gb18030", + Self::Big5 => "big5", + Self::ShiftJis => "shift-jis", + Self::EucJp => "euc-jp", + Self::EucKr => "euc-kr", + Self::Windows874 => "windows-874", + Self::Windows1250 => "windows-1250", + Self::Windows1251 => "windows-1251", + Self::Windows1252 => "windows-1252", + Self::Windows1253 => "windows-1253", + Self::Windows1254 => "windows-1254", + Self::Windows1255 => "windows-1255", + Self::Windows1256 => "windows-1256", + Self::Windows1257 => "windows-1257", + Self::Windows1258 => "windows-1258", + Self::Koi8R => "koi8-r", + } + } + + /// Parses a stable id or an accepted alias, case-insensitively. + /// + /// # Errors + /// + /// `InvalidRequest` naming the supported ids when `value` is none of them. + pub fn parse(value: &str) -> Result { + let encoding = match value.trim().to_ascii_lowercase().as_str() { + "utf-8" | "utf8" => Self::Utf8, + "gbk" | "cp936" => Self::Gbk, + "gb18030" => Self::Gb18030, + "big5" | "cp950" => Self::Big5, + "shift-jis" | "shift_jis" | "sjis" | "cp932" => Self::ShiftJis, + "euc-jp" | "eucjp" => Self::EucJp, + "euc-kr" | "euckr" | "cp949" => Self::EucKr, + "windows-874" | "cp874" => Self::Windows874, + "windows-1250" | "cp1250" => Self::Windows1250, + "windows-1251" | "cp1251" => Self::Windows1251, + // ISO-8859-1 resolves to Windows-1252, as in the WHATWG standard. + "windows-1252" | "cp1252" | "iso-8859-1" | "latin1" => Self::Windows1252, + "windows-1253" | "cp1253" => Self::Windows1253, + "windows-1254" | "cp1254" => Self::Windows1254, + "windows-1255" | "cp1255" => Self::Windows1255, + "windows-1256" | "cp1256" => Self::Windows1256, + "windows-1257" | "cp1257" => Self::Windows1257, + "windows-1258" | "cp1258" => Self::Windows1258, + "koi8-r" | "koi8r" => Self::Koi8R, + _ => { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Unsupported output encoding", + ) + .with_details(format!( + "'{value}' is not one of: {}", + OUTPUT_ENCODINGS.map(Self::id).join(", ") + ))) + } + }; + Ok(encoding) + } + + fn codec(self) -> &'static Encoding { + match self { + Self::Utf8 => UTF_8, + Self::Gbk => GBK, + Self::Gb18030 => GB18030, + Self::Big5 => BIG5, + Self::ShiftJis => SHIFT_JIS, + Self::EucJp => EUC_JP, + Self::EucKr => EUC_KR, + Self::Windows874 => WINDOWS_874, + Self::Windows1250 => WINDOWS_1250, + Self::Windows1251 => WINDOWS_1251, + Self::Windows1252 => WINDOWS_1252, + Self::Windows1253 => WINDOWS_1253, + Self::Windows1254 => WINDOWS_1254, + Self::Windows1255 => WINDOWS_1255, + Self::Windows1256 => WINDOWS_1256, + Self::Windows1257 => WINDOWS_1257, + Self::Windows1258 => WINDOWS_1258, + Self::Koi8R => KOI8_R, + } + } +} + +/// How one console's bytes become text: the `encoding` of `outputStyle.decode`, and the request +/// of `outputEncoding.resolve`. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OutputEncodingPolicy { + /// `auto`, or the id of the one encoding every line is decoded with. Absent is `auto`. + #[serde(default)] + pub setting: Option, + /// The encoding the starter of the process declared it writes, tried first in `auto`. + #[serde(default)] + pub declared: Option, + /// Whether the host is Windows. In `auto`, Windows tries GBK after UTF-8; other hosts + /// use UTF-8 alone unless the run declares an encoding. This does not inspect the locale. + #[serde(default)] + pub windows: bool, +} + +impl OutputEncodingPolicy { + /// The encodings a line is tried in, in order, without repeats; never empty. + /// + /// # Errors + /// + /// `InvalidRequest` when `setting` or `declared` is not a supported id or alias. + pub fn candidates(&self) -> Result, CoreError> { + if let Some(setting) = self.setting.as_deref() { + if !setting.trim().eq_ignore_ascii_case("auto") { + return Ok(vec![OutputEncoding::parse(setting)?]); + } + } + let mut candidates = Vec::with_capacity(3); + if let Some(declared) = self.declared.as_deref() { + candidates.push(OutputEncoding::parse(declared)?); + } + candidates.push(OutputEncoding::Utf8); + if self.windows { + candidates.push(OutputEncoding::Gbk); + } + let mut unique = Vec::with_capacity(candidates.len()); + for encoding in candidates { + if !unique.contains(&encoding) { + unique.push(encoding); + } + } + Ok(unique) + } +} + +/// `outputEncoding.resolve` answer: what a policy decodes with, for a settings page. +#[derive(Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ResolveOutputEncodingResponse { + /// The ids a line is tried in, in order. + pub candidates: Vec<&'static str>, + /// Every id a setting may choose, in menu order. + pub encodings: Vec<&'static str>, +} + +/// `outputEncoding.resolve`: the encodings a policy tries, and every encoding it may choose. +/// +/// # Errors +/// +/// `InvalidRequest` when the policy names an unsupported encoding. +pub fn resolve_output_encoding( + policy: OutputEncodingPolicy, +) -> Result { + Ok(ResolveOutputEncodingResponse { + candidates: policy + .candidates()? + .into_iter() + .map(OutputEncoding::id) + .collect(), + encodings: OUTPUT_ENCODINGS.map(OutputEncoding::id).to_vec(), + }) +} + +/// Decodes one line's bytes, without its line ending, with the first candidate they are valid +/// in; when they are valid in none, with the candidate that replaces the fewest characters, the +/// earlier on a tie. Unless `last`, a character the bytes end inside is left out instead of +/// being replaced: the line is still being written. +pub(crate) fn decode_line(bytes: &[u8], candidates: &[OutputEncoding], last: bool) -> String { + if bytes.is_ascii() { + // Every candidate is ASCII-compatible. + return bytes.iter().map(|&byte| char::from(byte)).collect(); + } + for &encoding in candidates { + if let Some(text) = decode_strict(encoding, bytes, last) { + return text; + } + } + let mut best: Option<(String, usize)> = None; + for &encoding in candidates { + let (text, replaced) = decode_lossy(encoding, bytes, last); + if best.as_ref().is_none_or(|(_, fewest)| replaced < *fewest) { + best = Some((text, replaced)); + } + } + best.map(|(text, _)| text).unwrap_or_default() +} + +/// How much of the start of `bytes` ends on a character boundary in some candidate: all of +/// them, or up to the three bytes a character can still lack. When no candidate decodes even +/// that, all of them, since the line is replaced in any case. +pub(crate) fn complete_prefix(bytes: &[u8], candidates: &[OutputEncoding]) -> usize { + (0..=3usize.min(bytes.len())) + .map(|missing| bytes.len() - missing) + .find(|&end| { + candidates + .iter() + .any(|&encoding| decode_strict(encoding, &bytes[..end], true).is_some()) + }) + .unwrap_or(bytes.len()) +} + +/// `bytes` decoded with `encoding`, or `None` when they are not valid in it. Unless `last`, a +/// character they end inside is valid and left out. +fn decode_strict(encoding: OutputEncoding, bytes: &[u8], last: bool) -> Option { + if encoding == OutputEncoding::Utf8 { + return match std::str::from_utf8(bytes) { + Ok(text) => Some(text.to_owned()), + Err(error) if !last && error.error_len().is_none() => { + std::str::from_utf8(&bytes[..error.valid_up_to()]) + .ok() + .map(str::to_owned) + } + Err(_) => None, + }; + } + let mut decoder = encoding.codec().new_decoder_without_bom_handling(); + let mut text = + String::with_capacity(decoder.max_utf8_buffer_length_without_replacement(bytes.len())?); + match decoder.decode_to_string_without_replacement(bytes, &mut text, last) { + (DecoderResult::InputEmpty, _) => Some(text), + _ => None, + } +} + +/// `bytes` decoded with `encoding`, invalid sequences replaced by U+FFFD, and how many were +/// replaced. Unless `last`, a character they end inside is left out. +fn decode_lossy(encoding: OutputEncoding, bytes: &[u8], last: bool) -> (String, usize) { + let mut decoder = encoding.codec().new_decoder_without_bom_handling(); + let mut text = String::new(); + let mut rest = bytes; + let mut replaced = false; + loop { + text.reserve( + decoder + .max_utf8_buffer_length(rest.len()) + .unwrap_or(rest.len()), + ); + let (result, read, replaced_now) = decoder.decode_to_string(rest, &mut text, last); + replaced |= replaced_now; + rest = &rest[read..]; + if result == CoderResult::InputEmpty { + break; + } + } + let count = if replaced { + text.matches('\u{fffd}').count() + } else { + 0 + }; + (text, count) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn gbk(text: &str) -> Vec { + GBK.encode(text).0.into_owned() + } + + fn auto(windows: bool) -> Vec { + OutputEncodingPolicy { + windows, + ..OutputEncodingPolicy::default() + } + .candidates() + .unwrap() + } + + #[test] + fn windows_preserves_utf8_and_falls_back_to_gbk() { + let candidates = auto(true); + assert_eq!(candidates, [OutputEncoding::Utf8, OutputEncoding::Gbk]); + assert_eq!( + decode_line("构建成功".as_bytes(), &candidates, true), + "构建成功" + ); + assert_eq!(decode_line(&gbk("构建成功"), &candidates, true), "构建成功"); + } + + #[test] + fn other_hosts_use_utf8_without_gbk_fallback() { + assert_eq!( + decode_line(&gbk("中"), &auto(false), true), + "\u{fffd}\u{fffd}" + ); + } + + #[test] + fn a_declared_encoding_comes_first_and_a_setting_is_the_only_one() { + let declared = OutputEncodingPolicy { + declared: Some("Shift_JIS".to_owned()), + windows: false, + ..OutputEncodingPolicy::default() + }; + assert_eq!( + declared.candidates().unwrap(), + [OutputEncoding::ShiftJis, OutputEncoding::Utf8] + ); + let fixed = OutputEncodingPolicy { + setting: Some("big5".to_owned()), + ..declared + }; + assert_eq!(fixed.candidates().unwrap(), [OutputEncoding::Big5]); + let unknown = OutputEncodingPolicy { + setting: Some("utf-16le".to_owned()), + ..OutputEncodingPolicy::default() + }; + assert!(matches!( + unknown.candidates().unwrap_err().code, + ErrorCode::InvalidRequest + )); + } + + #[test] + fn an_unfinished_character_is_left_out_until_the_line_ends() { + let bytes = gbk("中文"); + let candidates = auto(true); + assert_eq!(decode_line(&bytes[..3], &candidates, false), "中"); + assert_eq!(complete_prefix(&bytes[..3], &candidates), 2); + assert_eq!(complete_prefix(&bytes, &candidates), 4); + } + + #[test] + fn a_line_valid_in_no_candidate_takes_the_one_that_replaces_least() { + // GBK text with one stray byte: UTF-8 would replace every character. + let mut bytes = gbk("编译错误"); + bytes.push(0xff); + assert_eq!(decode_line(&bytes, &auto(true), true), "编译错误\u{fffd}"); + } + + #[test] + fn every_id_parses_back() { + for encoding in OUTPUT_ENCODINGS { + assert_eq!(OutputEncoding::parse(encoding.id()).unwrap(), encoding); + } + } +} diff --git a/rust/crates/terminal/src/lib.rs b/rust/crates/terminal/src/lib.rs index e020f83f..32053e57 100644 --- a/rust/crates/terminal/src/lib.rs +++ b/rust/crates/terminal/src/lib.rs @@ -1,8 +1,13 @@ //! Terminal output interpretation shared by the native hosts. +mod encoding; mod link; mod style; +pub use encoding::{ + resolve_output_encoding, OutputEncoding, OutputEncodingPolicy, ResolveOutputEncodingResponse, + OUTPUT_ENCODINGS, +}; pub use link::{parse_link_targets, ParseLinkTargetsRequest}; pub use style::{ decode_output_style, DecodeOutputStyleRequest, DecodeOutputStyleResponse, OutputColor, diff --git a/rust/crates/terminal/src/style.rs b/rust/crates/terminal/src/style.rs index 7a6189db..fd78e154 100644 --- a/rust/crates/terminal/src/style.rs +++ b/rust/crates/terminal/src/style.rs @@ -7,15 +7,23 @@ //! how a carriage return rewrites a line and how long a line may grow. The host owns the palette //! and how a style is drawn. //! +//! A host passes either text or the bytes the process wrote. Bytes are cut into lines at `\n` +//! and `\r` first, and each line is decoded with the encoding it is valid in (see +//! [`crate::encoding`]). A line the output has not ended yet is held as bytes until it ends, +//! because its encoding is only known then; the answer shows it decoded so far. +//! //! Decoding keeps no state between calls. Every answer returns the state the next chunk of the //! same console continues from: an escape sequence the chunk ended inside, the style in effect, -//! a pending carriage return and the line the output has not ended yet. Splitting the same output -//! into different chunks therefore never changes the lines. +//! a pending carriage return, the line the output has not ended yet and the bytes still held. +//! Splitting the same output into different chunks therefore never changes the lines. +use base64::Engine as _; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; -/// Largest chunk one request may carry, in UTF-8 bytes. +use crate::encoding::{complete_prefix, decode_line, OutputEncoding, OutputEncodingPolicy}; + +/// Largest chunk one request may carry, in bytes (UTF-8 bytes for text). const MAX_TEXT_BYTES: usize = 1 << 20; /// Longest line Core keeps, in UTF-8 bytes; longer output continues on the next line. pub const MAX_LINE_BYTES: usize = 16 << 10; @@ -23,6 +31,11 @@ pub const MAX_LINE_BYTES: usize = 16 << 10; pub const MAX_SPANS_PER_LINE: usize = 512; /// Longest unfinished escape sequence carried to the next chunk, in UTF-8 bytes. const MAX_PENDING_BYTES: usize = 4096; +/// Most bytes of an unfinished line held back. A byte never decodes to more than three UTF-8 +/// bytes, so held bytes always fit in the open line they are shown on. +const MAX_HELD_BYTES: usize = MAX_LINE_BYTES / 3; +/// Standard base64, the form of a request's bytes and of the held bytes. +const BASE64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; const ESC: char = '\u{1b}'; @@ -157,13 +170,14 @@ pub struct OutputLine { /// Where one console's output stands after a chunk. /// -/// The host passes it back unchanged with the next chunk of the same console and shows `line` -/// after the finished lines; it reads nothing else in it. Dropping the state ends the console: -/// the open line stays as it is and an unfinished escape sequence is discarded. +/// The host passes it back unchanged with the next chunk of the same console and reads nothing +/// in it; it shows the answer's `open` line. Dropping the state ends the console: the open line +/// stays as the host shows it and an unfinished escape sequence is discarded. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct OutputStyleState { - /// The line the output has not ended yet; empty text when the last chunk ended a line. + /// The decoded part of the line the output has not ended yet; empty text when the last + /// chunk ended a line. #[serde(default)] pub line: OutputLine, /// The style the next character is drawn with. @@ -175,15 +189,28 @@ pub struct OutputStyleState { /// A carriage return moved to the start of `line`: the next printed character replaces it. #[serde(default, skip_serializing_if = "is_false")] pub carriage: bool, + /// The bytes that continue `line` and are not decoded yet, in standard base64; only in + /// answers to bytes. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub held: String, } /// `outputStyle.decode` request: the next chunk of one console and the state the previous -/// chunk left. A console's first chunk carries no state. -#[derive(Debug, Deserialize)] +/// chunk left. A console's first chunk carries no state; every chunk of one console carries +/// the same kind of input, text or bytes. +#[derive(Debug, Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct DecodeOutputStyleRequest { - /// The chunk, at most 1 MiB of UTF-8. - pub text: String, + /// The chunk as text, at most 1 MiB of UTF-8. Exactly one of `text` and `bytes` is present. + #[serde(default)] + pub text: Option, + /// The chunk as the bytes the process wrote, in standard base64, at most 1 MiB decoded. + #[serde(default)] + pub bytes: Option, + /// How the bytes become text; absent is automatic with no declared encoding and no Windows + /// compatibility. Only with `bytes`. + #[serde(default)] + pub encoding: Option, /// The state the previous answer for this console returned, unchanged. #[serde(default)] pub state: Option, @@ -193,9 +220,12 @@ pub struct DecodeOutputStyleRequest { #[derive(Debug, Serialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct DecodeOutputStyleResponse { - /// The lines this chunk ended, oldest first; the first continues the request's open line. + /// The lines this chunk ended, oldest first; the first continues the previous open line. pub lines: Vec, - /// The state for the next chunk; its `line` is the line still open. + /// The line still open, as the host shows it after the finished lines. For bytes it + /// includes the held bytes decoded so far, so a later answer may show them differently. + pub open: OutputLine, + /// The state for the next chunk. pub state: OutputStyleState, } @@ -209,54 +239,125 @@ pub struct DecodeOutputStyleResponse { /// DCS, APC, PM, SOS) and escape, and every control character except tab, is dropped; the text /// between OSC 8 hyperlink markers is kept. Lines longer than 16 KiB continue on the next line. /// +/// Bytes are decoded one line at a time, a line ended by `\n` or `\r`, with the first of the +/// policy's candidates the line is valid in. An unfinished line is held until it ends; one that +/// grows past what its open line can show is decoded up to its last character boundary. +/// /// # Errors /// -/// `InvalidRequest` when the chunk is larger than 1 MiB or the state is not one this command -/// returned: an open line over the limits, ranges outside the line or out of order, or a -/// pending sequence that is not an escape. +/// `InvalidRequest` when the request has neither or both of `text` and `bytes`, carries an +/// encoding with text, names an unsupported encoding or has a chunk larger than 1 MiB, or when +/// the state is not one this command returned for the same kind of input: an open line over +/// the limits, ranges outside the line or out of order, a pending sequence that is not an +/// escape, or held bytes that are not the base64 of an unfinished line. pub fn decode_output_style( request: DecodeOutputStyleRequest, ) -> Result { - if request.text.len() > MAX_TEXT_BYTES { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "The output chunk is too large.", - )); - } + let invalid = |message: &'static str| CoreError::new(ErrorCode::InvalidRequest, message); let state = request.state.unwrap_or_default(); let units = validated_units(&state)?; - let mut input = state.pending; - input.push_str(&request.text); - let mut decoder = Decoder { - line: LineBuilder { - text: state.line.text, - units, - spans: state.line.spans, - }, - style: state.style, - carriage: state.carriage, - finished: Vec::new(), - }; - let pending = decoder.run(&input); - Ok(DecodeOutputStyleResponse { - lines: decoder.finished, - state: OutputStyleState { - line: decoder.line.take(), + match (request.text, request.bytes) { + (Some(text), None) => { + if request.encoding.is_some() { + return Err(invalid("An output encoding applies only to bytes.")); + } + if text.len() > MAX_TEXT_BYTES { + return Err(invalid("The output chunk is too large.")); + } + if !state.held.is_empty() { + return Err(invalid_state()); + } + let (mut decoder, pending) = Decoder::resume(state, units); + let pending = decoder.run_after(pending, &text); + let open = decoder.line.snapshot(); + Ok(decoder.answer(open, pending, &[])) + } + (None, Some(bytes)) => { + if bytes.len() > MAX_TEXT_BYTES.div_ceil(3) * 4 { + return Err(invalid("The output chunk is too large.")); + } + let bytes = BASE64.decode(bytes).map_err(|error| { + invalid("The output bytes are not base64.").with_details(error.to_string()) + })?; + if bytes.len() > MAX_TEXT_BYTES { + return Err(invalid("The output chunk is too large.")); + } + let candidates = request.encoding.unwrap_or_default().candidates()?; + decode_bytes(state, units, &bytes, &candidates) + } + _ => Err(invalid( + "An output chunk has exactly one of text and bytes.", + )), + } +} + +/// Decodes a chunk of bytes: the lines it ends are decoded and fed to the decoder; the rest is +/// held and shown decoded so far. +fn decode_bytes( + mut state: OutputStyleState, + units: u32, + bytes: &[u8], + candidates: &[OutputEncoding], +) -> Result { + let mut input = BASE64 + .decode(std::mem::take(&mut state.held)) + .map_err(|_| invalid_state())?; + if input.len() > MAX_HELD_BYTES || input.iter().copied().any(is_line_break) { + return Err(invalid_state()); + } + input.extend_from_slice(bytes); + let ended = input + .iter() + .copied() + .rposition(is_line_break) + .map_or(0, |at| at + 1); + let mut text = String::new(); + for line in input[..ended].split_inclusive(|byte| is_line_break(*byte)) { + let (content, ending) = line.split_at(line.len() - 1); + text.push_str(&decode_line(content, candidates, true)); + text.push(char::from(ending[0])); + } + let (mut decoder, pending) = Decoder::resume(state, units); + let mut pending = decoder.run_after(pending, &text); + let mut held = &input[ended..]; + if decoder.line.text.len() + 3 * held.len() > MAX_LINE_BYTES { + // The open line could not show the held bytes: decode what ends on a character. + let end = complete_prefix(held, candidates); + pending = decoder.run_after(pending, &decode_line(&held[..end], candidates, true)); + held = &held[end..]; + } + let mut open = decoder.line.snapshot(); + if !held.is_empty() { + let mut preview = Decoder { + line: decoder.line.clone(), style: decoder.style, - pending, carriage: decoder.carriage, - }, - }) + finished: Vec::new(), + }; + preview.run_after(pending.clone(), &decode_line(held, candidates, false)); + // The few bytes left after an overlong line may not fit its open line; they show once + // the line ends. + if preview.finished.is_empty() { + open = preview.line.take(); + } + } + Ok(decoder.answer(open, pending, held)) +} + +fn is_line_break(byte: u8) -> bool { + byte == b'\n' || byte == b'\r' +} + +fn invalid_state() -> CoreError { + CoreError::new( + ErrorCode::InvalidRequest, + "The output style state is invalid.", + ) } /// Checks a state the host passed back and returns the UTF-16 length of its open line. fn validated_units(state: &OutputStyleState) -> Result { - let invalid = || { - CoreError::new( - ErrorCode::InvalidRequest, - "The output style state is invalid.", - ) - }; + let invalid = invalid_state; let line = &state.line; if line.text.len() > MAX_LINE_BYTES || line.spans.len() > MAX_SPANS_PER_LINE @@ -282,6 +383,7 @@ fn validated_units(state: &OutputStyleState) -> Result { /// The open line while a chunk is decoded. Its UTF-16 length is kept so a range never needs /// a rescan of the text. +#[derive(Clone)] struct LineBuilder { text: String, units: u32, @@ -303,6 +405,13 @@ impl LineBuilder { } } + fn snapshot(&self) -> OutputLine { + OutputLine { + text: self.text.clone(), + spans: self.spans.clone(), + } + } + /// Appends one character drawn with `style`, extending the last range when it ends here /// with the same style. fn push(&mut self, ch: char, style: &OutputStyle) { @@ -352,6 +461,53 @@ enum Scan<'a> { } impl Decoder { + /// Continues the console a validated state left, and returns the unfinished escape + /// sequence the state carries. + fn resume(state: OutputStyleState, units: u32) -> (Self, String) { + let decoder = Self { + line: LineBuilder { + text: state.line.text, + units, + spans: state.line.spans, + }, + style: state.style, + carriage: state.carriage, + finished: Vec::new(), + }; + (decoder, state.pending) + } + + /// Decodes `text` after the unfinished escape sequence `pending` and returns the one it + /// ends inside, if any. + fn run_after(&mut self, mut pending: String, text: &str) -> String { + pending.push_str(text); + self.run(&pending) + } + + /// The answer: the finished lines, the line shown open and the state to continue from. + fn answer( + mut self, + open: OutputLine, + pending: String, + held: &[u8], + ) -> DecodeOutputStyleResponse { + DecodeOutputStyleResponse { + lines: std::mem::take(&mut self.finished), + open, + state: OutputStyleState { + line: self.line.take(), + style: self.style, + pending, + carriage: self.carriage, + held: if held.is_empty() { + String::new() + } else { + BASE64.encode(held) + }, + }, + } + } + /// Decodes `input` and returns the unfinished escape sequence it ends inside, if any. fn run(&mut self, input: &str) -> String { let mut index = 0; @@ -651,16 +807,57 @@ mod tests { let mut state = None; for chunk in chunks { let response = decode_output_style(DecodeOutputStyleRequest { - text: (*chunk).to_owned(), + text: Some((*chunk).to_owned()), state: state.take(), + ..DecodeOutputStyleRequest::default() }) .unwrap(); + assert_eq!(response.open, response.state.line); lines.extend(response.lines); state = Some(response.state); } (lines, state.unwrap()) } + /// Decodes byte chunks of one console and returns the lines, the last open line and the + /// last state. + fn decode_bytes( + chunks: &[&[u8]], + encoding: &OutputEncodingPolicy, + ) -> (Vec, OutputLine, OutputStyleState) { + let mut lines = Vec::new(); + let mut open = OutputLine::default(); + let mut state = None; + for chunk in chunks { + let response = decode_output_style(DecodeOutputStyleRequest { + bytes: Some(BASE64.encode(chunk)), + encoding: Some(encoding.clone()), + state: state.take(), + ..DecodeOutputStyleRequest::default() + }) + .unwrap(); + lines.extend(response.lines); + open = response.open; + state = Some(response.state); + } + (lines, open, state.unwrap()) + } + + fn windows_chinese() -> OutputEncodingPolicy { + OutputEncodingPolicy { + windows: true, + ..OutputEncodingPolicy::default() + } + } + + fn gbk(text: &str) -> Vec { + encoding_rs::GBK.encode(text).0.into_owned() + } + + fn texts(lines: &[OutputLine]) -> Vec<&str> { + lines.iter().map(|line| line.text.as_str()).collect() + } + fn style(foreground: u8, bold: bool) -> OutputStyle { OutputStyle { foreground: Some(OutputColor::Index(foreground)), @@ -726,7 +923,7 @@ mod tests { #[test] fn a_state_with_ranges_outside_its_line_is_rejected() { let error = decode_output_style(DecodeOutputStyleRequest { - text: String::new(), + text: Some(String::new()), state: Some(OutputStyleState { line: OutputLine { text: "ab".to_owned(), @@ -738,11 +935,119 @@ mod tests { }, ..OutputStyleState::default() }), + ..DecodeOutputStyleRequest::default() }) .unwrap_err(); assert!(matches!(error.code, ErrorCode::InvalidRequest)); } + #[test] + fn every_split_of_mixed_encoding_bytes_decodes_the_same_lines() { + // A Windows build prints its own UTF-8 lines and a JVM's GBK lines, coloured, with a + // progress rewrite; a cut anywhere, inside a character or an escape, changes nothing. + let mut bytes = b"\x1b[1;34m[INFO]\x1b[m ".to_vec(); + bytes.extend(gbk("测试通过")); + bytes.extend("\r\n构建 ✓\n".as_bytes()); + bytes.extend(gbk("下载 10%")); + bytes.extend(b"\r"); + bytes.extend(gbk("下载 100%")); + let policy = windows_chinese(); + let (whole, whole_open, whole_state) = decode_bytes(&[&bytes], &policy); + assert_eq!(texts(&whole), ["[INFO] 测试通过", "构建 ✓"]); + assert_eq!(whole_open.text, "下载 100%"); + for split in 1..bytes.len() { + let (lines, open, state) = decode_bytes(&[&bytes[..split], &bytes[split..]], &policy); + assert_eq!(lines, whole, "split at {split}"); + assert_eq!(open, whole_open, "split at {split}"); + assert_eq!(state, whole_state, "split at {split}"); + } + } + + #[test] + fn an_unfinished_line_shows_what_is_decoded_so_far() { + let bytes = gbk("编码"); + let (lines, open, state) = decode_bytes(&[&bytes[..3]], &windows_chinese()); + assert!(lines.is_empty()); + assert_eq!(open.text, "编"); + assert!(state.line.text.is_empty()); + assert!(!state.held.is_empty()); + let (lines, _, _) = decode_bytes(&[&bytes[..3], &bytes[3..], b"\n"], &windows_chinese()); + assert_eq!(texts(&lines), ["编码"]); + } + + #[test] + fn a_fixed_encoding_decodes_every_line_with_it() { + let big5 = encoding_rs::BIG5.encode("編譯").0.into_owned(); + let policy = OutputEncodingPolicy { + setting: Some("big5".to_owned()), + windows: true, + ..OutputEncodingPolicy::default() + }; + let mut bytes = big5.clone(); + bytes.push(b'\n'); + let (lines, _, _) = decode_bytes(&[&bytes], &policy); + assert_eq!(texts(&lines), ["編譯"]); + // Automatic decoding on Windows would not read Big5 as Big5. + let (lines, _, _) = decode_bytes(&[&bytes], &windows_chinese()); + assert_ne!(texts(&lines), ["編譯"]); + } + + #[test] + fn an_overlong_unfinished_line_is_decoded_at_a_character_boundary() { + let line = gbk(&"中".repeat(MAX_HELD_BYTES)); + let (lines, open, state) = decode_bytes(&[&line[..line.len() - 1]], &windows_chinese()); + assert!(lines.is_empty()); + assert!(open.text.chars().all(|ch| ch == '中')); + // Everything up to the last whole character is decoded; its lead byte is held. + assert_eq!(BASE64.decode(&state.held).unwrap(), [line[line.len() - 2]]); + let (lines, _, _) = decode_bytes( + &[&line[..line.len() - 1], &line[line.len() - 1..], b"\n"], + &windows_chinese(), + ); + let joined: String = lines.iter().map(|line| line.text.as_str()).collect(); + assert_eq!(joined, "中".repeat(MAX_HELD_BYTES)); + } + + #[test] + fn a_request_has_exactly_one_kind_of_input() { + let both = DecodeOutputStyleRequest { + text: Some(String::new()), + bytes: Some(String::new()), + ..DecodeOutputStyleRequest::default() + }; + let encoding_with_text = DecodeOutputStyleRequest { + text: Some(String::new()), + encoding: Some(windows_chinese()), + ..DecodeOutputStyleRequest::default() + }; + let held_with_text = DecodeOutputStyleRequest { + text: Some(String::new()), + state: Some(OutputStyleState { + held: BASE64.encode("a"), + ..OutputStyleState::default() + }), + ..DecodeOutputStyleRequest::default() + }; + let held_line_break = DecodeOutputStyleRequest { + bytes: Some(String::new()), + state: Some(OutputStyleState { + held: BASE64.encode("a\n"), + ..OutputStyleState::default() + }), + ..DecodeOutputStyleRequest::default() + }; + for request in [ + DecodeOutputStyleRequest::default(), + both, + encoding_with_text, + held_with_text, + held_line_break, + ] { + let error = decode_output_style(request).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + } + } + #[test] fn colours_cross_the_wire_as_index_or_hex() { let color: OutputColor = serde_json::from_str(r##"{"rgb":"#0a0B0c"}"##).unwrap(); diff --git a/rust/fixtures/terminal/output-encoding-v1.json b/rust/fixtures/terminal/output-encoding-v1.json new file mode 100644 index 00000000..21904863 --- /dev/null +++ b/rust/fixtures/terminal/output-encoding-v1.json @@ -0,0 +1,288 @@ +{ + "version": 1, + "description": "Console output bytes. decode: each case sends its chunks (the bytes in hexadecimal) to outputStyle.decode as base64 bytes with the case's encoding policy, in order, passing back the state each answer returned; lines are all finished lines, oldest first, and open is the last answer's open line. resolve: outputEncoding.resolve with each policy returns the candidates, or fails with the error code; encodings is the list every resolve answer returns.", + "encodings": [ + "utf-8", + "gbk", + "gb18030", + "big5", + "shift-jis", + "euc-jp", + "euc-kr", + "windows-874", + "windows-1250", + "windows-1251", + "windows-1252", + "windows-1253", + "windows-1254", + "windows-1255", + "windows-1256", + "windows-1257", + "windows-1258", + "koi8-r" + ], + "decode": [ + { + "name": "a utf-8 line and a gbk line", + "encoding": { + "windows": true + }, + "chunks": [ + "e7bc96e8af910a", + "b9b9bda8b3c9b9a60d0a" + ], + "lines": [ + { + "text": "编译" + }, + { + "text": "构建成功" + } + ], + "open": { + "text": "" + } + }, + { + "name": "gbk character split across chunks", + "encoding": { + "windows": true + }, + "chunks": [ + "b9b9bd", + "a80a" + ], + "lines": [ + { + "text": "构建" + } + ], + "open": { + "text": "" + } + }, + { + "name": "unfinished gbk line is shown decoded so far", + "encoding": { + "windows": true + }, + "chunks": [ + "b9b9bda8b3" + ], + "lines": [], + "open": { + "text": "构建" + } + }, + { + "name": "outside Windows a gbk line is replaced", + "chunks": [ + "b9b9bda80a" + ], + "lines": [ + { + "text": "����" + } + ], + "open": { + "text": "" + } + }, + { + "name": "a valid utf-8 line stays utf-8 on Windows", + "encoding": { + "windows": true + }, + "chunks": [ + "c3a90a" + ], + "lines": [ + { + "text": "é" + } + ], + "open": { + "text": "" + } + }, + { + "name": "a declared encoding is tried first", + "encoding": { + "declared": "gbk" + }, + "chunks": [ + "c3a90a" + ], + "lines": [ + { + "text": "茅" + } + ], + "open": { + "text": "" + } + }, + { + "name": "a fixed encoding decodes every line", + "encoding": { + "setting": "windows-1252", + "declared": "gbk", + "windows": true + }, + "chunks": [ + "c3a90a" + ], + "lines": [ + { + "text": "é" + } + ], + "open": { + "text": "" + } + }, + { + "name": "colours around gbk text", + "encoding": { + "windows": true + }, + "chunks": [ + "1b5b33326db3c9b9a61b5b6d0d0a" + ], + "lines": [ + { + "text": "成功", + "spans": [ + { + "start": 0, + "length": 2, + "style": { + "foreground": { + "index": 2 + } + } + } + ] + } + ], + "open": { + "text": "" + } + }, + { + "name": "shift-jis by explicit declaration", + "encoding": { + "declared": "shift-jis" + }, + "chunks": [ + "93fa967b0a" + ], + "lines": [ + { + "text": "日本" + } + ], + "open": { + "text": "" + } + } + ], + "resolve": [ + { + "name": "nothing is utf-8", + "policy": {}, + "candidates": [ + "utf-8" + ] + }, + { + "name": "windows falls back to gbk", + "policy": { + "windows": true + }, + "candidates": [ + "utf-8", + "gbk" + ] + }, + { + "name": "non-windows has no gbk fallback", + "policy": { + "windows": false + }, + "candidates": [ + "utf-8" + ] + }, + { + "name": "a declared encoding comes first", + "policy": { + "setting": "auto", + "declared": "GBK", + "windows": true + }, + "candidates": [ + "gbk", + "utf-8" + ] + }, + { + "name": "a fixed encoding is alone", + "policy": { + "setting": "big5", + "windows": true + }, + "candidates": [ + "big5" + ] + }, + { + "name": "a utf-8 declaration keeps windows gbk compatibility", + "policy": { + "declared": "utf-8", + "windows": true + }, + "candidates": [ + "utf-8", + "gbk" + ] + }, + { + "name": "an alias names its encoding", + "policy": { + "setting": "cp936" + }, + "candidates": [ + "gbk" + ] + }, + { + "name": "utf-16 is not an output encoding", + "policy": { + "setting": "utf-16" + }, + "error": "invalid_request" + }, + { + "name": "an unknown declaration is rejected", + "policy": { + "declared": "ebcdic" + }, + "error": "invalid_request" + }, + { + "name": "an unknown member is rejected", + "policy": { + "Windows": true + }, + "error": "invalid_request" + }, + { + "name": "a code page is not a default policy", + "policy": { + "codePage": 936 + }, + "error": "invalid_request" + } + ] +} diff --git a/rust/fixtures/terminal/output-style-v1.json b/rust/fixtures/terminal/output-style-v1.json index 2b205361..f4d76da8 100644 --- a/rust/fixtures/terminal/output-style-v1.json +++ b/rust/fixtures/terminal/output-style-v1.json @@ -1,6 +1,6 @@ { "version": 1, - "description": "outputStyle.decode: each case sends its chunks in order, passing back the state each answer returned. lines are all finished lines, oldest first; open is the final state's line.", + "description": "outputStyle.decode: each case sends its chunks in order, passing back the state each answer returned. lines are all finished lines, oldest first; open is the last answer's open line, the same as its state's line.", "cases": [ { "name": "maven info line", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 4c7da40a..49cfc9c7 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -2350,6 +2350,20 @@ keys match `[A-Za-z_][A-Za-z0-9_]*` with at most 128 bytes, values are strings of at most 64 KiB without NUL. The complete JSON is bounded at 32 MiB. `workingDirectory` must be an existing workspace-relative directory inside the selected instance, including after resolving filesystem aliases. + +`outputEncoding` is optional: the character encoding the process writes to +stdout and stderr, for a provider that knows it, for example because it starts +the tool with a fixed output encoding. It is one of `utf-8`, `gbk`, `gb18030`, +`big5`, `shift-jis`, `euc-jp`, `euc-kr`, `windows-874`, `windows-1250` to +`windows-1258` and `koi8-r`, matched case-insensitively; the aliases `utf8`, +`cp936`, `cp950`, `shift_jis`, `sjis`, `cp932`, `eucjp`, `euckr`, `cp949`, +`cp874`, `cp1250` to `cp1258`, `iso-8859-1`, `latin1` (both `windows-1252`) +and `koi8r` are accepted, and the decoded plan carries the id. Any other +value, UTF-16 included, fails as `plugin.build.invalidOutput`. The host still +decodes each output line on its own: with the automatic console encoding +setting it tries the declared encoding first, then UTF-8, then GBK on Windows, and a fixed encoding the user chose overrides the +declaration. Leave it out when unsure; automatic decoding uses UTF-8 everywhere and falls back to GBK on Windows. + Unknown fields are ignored. The host calls `build.decodeRunPreparation` with its workspace root, instance root and raw result; any malformed plan fails as `plugin.build.invalidOutput` before executable resolution. @@ -4166,14 +4180,16 @@ context it started in has closed. - `label` is 1 to 256 characters without control characters. It titles the Run window entry. -- `process` is `{executable, arguments, workingDirectory, environment}`, all - four required. `executable` is `{kind: "tool", tool}`, a tool that the +- `process` is `{executable, arguments, workingDirectory, environment, + outputEncoding?}`, the first four required. `executable` is `{kind: "tool", tool}`, a tool that the manifest lists in `requiresTools` (the host resolves it through the [tool-definition layers](toolchains/README.md)), or `{kind: "packaged", path}`, a normalized relative path of a file inside the plugin package. Arguments, the working directory (relative to the workspace root and an existing directory inside it) and the environment have the bounds of - [run preparation](#provider-run-preparation). An unknown + [run preparation](#provider-run-preparation). `outputEncoding` declares the + encoding the process writes, as in run preparation; a value the host cannot + decode lines in is refused at `process.outputEncoding`. An unknown `process` field is refused. - `temporaryFiles` is at most four files of up to 4 MiB each. A file is `{name, contents}`, text the host writes as UTF-8, or `{name, base64}`, diff --git a/shared/plugins/contract/v1/fixtures/run/run-start.json b/shared/plugins/contract/v1/fixtures/run/run-start.json index a779efb5..ae31fc15 100644 --- a/shared/plugins/contract/v1/fixtures/run/run-start.json +++ b/shared/plugins/contract/v1/fixtures/run/run-start.json @@ -44,6 +44,28 @@ "temporaryFiles": [] } }, + { + "name": "a declared output encoding is kept as its id", + "params": { + "label": "Run legacy tool", + "process": { + "executable": { "kind": "tool", "tool": "interpreter" }, + "arguments": [], + "workingDirectory": ".", + "environment": {}, + "outputEncoding": "CP936" + } + }, + "start": { + "label": "Run legacy tool", + "executable": { "kind": "toolchain", "value": "interpreter" }, + "arguments": [], + "workingDirectory": ".", + "environment": {}, + "temporaryFiles": [], + "outputEncoding": "gbk" + } + }, { "name": "a debug connection and a rerun function are kept", "params": { @@ -188,6 +210,20 @@ }, "error": { "code": "plugin.run.invalidStart", "field": "process.shell" } }, + { + "name": "an output encoding the host cannot decode lines in", + "params": { + "label": "Run", + "process": { + "executable": { "kind": "tool", "tool": "interpreter" }, + "arguments": [], + "workingDirectory": ".", + "environment": {}, + "outputEncoding": "utf-16" + } + }, + "error": { "code": "plugin.run.invalidStart", "field": "process.outputEncoding" } + }, { "name": "a label with a line break", "params": { diff --git a/shared/plugins/guides/native-build-workflows.md b/shared/plugins/guides/native-build-workflows.md index 6dd2b78d..ed2ed25d 100644 --- a/shared/plugins/guides/native-build-workflows.md +++ b/shared/plugins/guides/native-build-workflows.md @@ -31,7 +31,7 @@ 构建与测试处理器使用调用上下文的 `run` 启动工具,取消或调用结束会结束它拥有的工具树。工具正常返回非零码仍是执行结果;异常属于协议或准备失败。不要启动脱离调用的进程,或用一条私有函数代替这些领域入口。 -运行准备先等待上游同步和必要构建,再返回 `executable`、原始 `arguments` 数组、工作区相对 `workingDirectory` 和 `environment`。`executable.kind` 只能是 `command`(宿主解析的裸命令名)或 `toolchain`(宿主工具链标识)。处理器不启动长期运行的应用;宿主校验后启动、停止并显示应用输出。构建失败、取消或旧结果失效时不能启动应用。 +运行准备先等待上游同步和必要构建,再返回 `executable`、原始 `arguments` 数组、工作区相对 `workingDirectory` 和 `environment`。`executable.kind` 只能是 `command`(宿主解析的裸命令名)或 `toolchain`(宿主工具链标识)。应用确定按某种非 UTF-8 编码输出时(例如固定写 GBK 的旧程序),可以加 `outputEncoding`,宿主解码控制台的每一行时先试它;不确定时不写。处理器不启动长期运行的应用;宿主校验后启动、停止并显示应用输出。构建失败、取消或旧结果失效时不能启动应用。 执行与测试请求的后端拒绝由 Core 报告为 `plugin.build.failed`。运行准备的 RPC 错误保留通用 LSP `serverError` 分类,不是带退出码的执行结果,也不使用私有函数的 `pluginErrorCode`。宿主在两种失败下都不能启动应用或改走旧命令。 @@ -129,7 +129,7 @@ The plugin reads the current project, test, and run facts from the upstream engi Build and test handlers start tools through the call context's `run`; cancellation or the end of the call ends the tool tree it owns. A tool that returns a non-zero code normally is still an execution result; an exception is a protocol or preparation failure. Do not start processes that outlive the call, and do not replace these domain entry points with a private function. -Run preparation first waits for upstream sync and any required build, then returns `executable`, the raw `arguments` array, a workspace-relative `workingDirectory`, and `environment`. `executable.kind` is only `command` (a bare command name the host resolves) or `toolchain` (a host toolchain identifier). The handler does not start a long-running application; the host validates the plan, then starts and stops the application and shows its output. A build failure, cancellation, or stale result must not start the application. +Run preparation first waits for upstream sync and any required build, then returns `executable`, the raw `arguments` array, a workspace-relative `workingDirectory`, and `environment`. `executable.kind` is only `command` (a bare command name the host resolves) or `toolchain` (a host toolchain identifier). When the application is known to write a non-UTF-8 encoding (for example an old program that always writes GBK), the plan can add `outputEncoding`, which the host tries first for every console line; leave it out when unsure. The handler does not start a long-running application; the host validates the plan, then starts and stops the application and shows its output. A build failure, cancellation, or stale result must not start the application. Core reports a backend rejection of an execute or test request as `plugin.build.failed`. An RPC error from run preparation keeps the generic LSP `serverError` classification; it is not an execution result with an exit code and does not use the private-function `pluginErrorCode`. In both failures the host must not start the application or fall back to an old command. diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 853c1f30..cc9e247b 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -118,7 +118,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-21 | `credentials/set` | 保存密钥,最多 16 KiB | `credentials.store` | 0 | | API-21 | `credentials/delete` | 删除密钥,没有保存过也返回 `null` | `credentials.store` | 0 | | API-22、API-25 | `languageServer/setStatus` | 在宿主状态界面显示插件自己的语言服务器准备状态(`preparing`、`ready`、`degraded`、`failed`,可带消息和百分比) | `languageServer.request` | 0 | -| API-23 | `run/start` | 启动宿主拥有的 Run 会话(Run 窗口条目、控制台、停止按钮);可执行文件只能是工具定义 ID 或插件包内文件,可带临时文件、调试和再次运行,返回 `runID` | `run.start` | 0 | +| API-23 | `run/start` | 启动宿主拥有的 Run 会话(Run 窗口条目、控制台、停止按钮);可执行文件只能是工具定义 ID 或插件包内文件,可带临时文件、输出编码、调试和再次运行,返回 `runID` | `run.start` | 0 | | API-23 | `run/stop` | 按 `runID` 或 `sessionID` 停止本插件启动的运行或调试会话;不带 `context` | `run.start` | 0 | | API-24 | `terminal/create` | 经执行确认创建插件自有原生终端,返回 `terminalID` 和 `generation` | `terminal.create` | 0 | | API-24 | `terminal/show` | 显示并选中本插件的终端 | `terminal.create` | 0 | @@ -130,6 +130,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-25 | `languageServer/request` | 向本插件自己的语言服务器发 JSON-RPC 请求,受会话策略检查,返回 `{value}` | `languageServer.request` | 0 | | API-25 | `languageServer/notify` | 向本插件自己的语言服务器发通知,返回 `{delivered}` | `languageServer.request` | 0 | | API-27 | `editor/registerActions` | 注册编辑器动作:把后端的普通函数绑定到文件范围(`selector`),返回 `subscriptionID` | `editor.actions`(同时需要 `documents.read`) | 0 | +| API-29 | `lithe/build/prepareRun`(提供者方法) | 准备宿主启动的运行计划,可选 `outputEncoding` 声明进程管道编码;参数、失败码和生命周期见[运行准备](../contract/v1/README.md#provider-run-preparation) | `process.build` | `litheBuild` 0、1 | | API-30 | `debug/start` | 在本插件自己声明的调试适配器上启动 launch 或 attach 调试会话,返回 `sessionID` | `debug.start` | 0 | | API-35 | `functions/providers` | 列出导出某函数、已启用、且不是调用方自己的插件及其导出版本 | 无清单权限,需在 `pluginFunctions.calls` 声明该函数 | 0 | | API-35 | `functions/invoke` | 经 Core 调用另一个插件导出的函数,可带 `parentOperationID` 标明所属调用链,返回 `{value}` | 无清单权限,需在 `pluginFunctions.calls` 声明该函数 | 0 | @@ -290,7 +291,7 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-21 | `credentials/set` | Stores a secret of at most 16 KiB | `credentials.store` | 0 | | API-21 | `credentials/delete` | Deletes a secret; also returns `null` when nothing was stored | `credentials.store` | 0 | | API-22, API-25 | `languageServer/setStatus` | Shows the plugin's own language server preparation state (`preparing`, `ready`, `degraded`, `failed`, optionally with a message and a percentage) in the host's status UI | `languageServer.request` | 0 | -| API-23 | `run/start` | Starts a host-owned Run session (Run window entry, console, Stop button); the executable can only be a tool-definition ID or a file inside the plugin package, and the call can carry temporary files, debugging, and rerun, and returns a `runID` | `run.start` | 0 | +| API-23 | `run/start` | Starts a host-owned Run session (Run window entry, console, Stop button); the executable can only be a tool-definition ID or a file inside the plugin package, and the call can carry temporary files, an output encoding, debugging, and rerun, and returns a `runID` | `run.start` | 0 | | API-23 | `run/stop` | Stops a run or debug session this plugin started, by `runID` or `sessionID`; takes no `context` | `run.start` | 0 | | API-24 | `terminal/create` | Creates a plugin-owned native terminal after execution consent and returns `terminalID` and `generation` | `terminal.create` | 0 | | API-24 | `terminal/show` | Shows and selects one of this plugin's terminals | `terminal.create` | 0 | @@ -302,6 +303,7 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-25 | `languageServer/request` | Sends a JSON-RPC request to the plugin's own language server, checked against the session policy, and returns `{value}` | `languageServer.request` | 0 | | API-25 | `languageServer/notify` | Sends a notification to the plugin's own language server and returns `{delivered}` | `languageServer.request` | 0 | | API-27 | `editor/registerActions` | Registers editor actions that bind an ordinary backend function to file ranges (`selector`) and returns a `subscriptionID` | `editor.actions` (also needs `documents.read`) | 0 | +| API-29 | `lithe/build/prepareRun` (provider method) | Prepares a host-owned launch plan; optional `outputEncoding` declares the process pipe encoding; see [run preparation](../contract/v1/README.md#provider-run-preparation) for params, failures and lifecycle | `process.build` | `litheBuild` 0, 1 | | API-30 | `debug/start` | Starts a launch or attach debug session on a debug adapter the plugin itself declares, and returns a `sessionID` | `debug.start` | 0 | | API-35 | `functions/providers` | Lists the enabled plugins, other than the caller, that export a function, with their exported versions | No manifest permission; the function must be declared in `pluginFunctions.calls` | 0 | | API-35 | `functions/invoke` | Calls a function another plugin exports, relayed by Core; can carry `parentOperationID` to name the call chain it belongs to, and returns `{value}` | No manifest permission; the function must be declared in `pluginFunctions.calls` | 0 | diff --git a/shared/plugins/reference/domains/backend.md b/shared/plugins/reference/domains/backend.md index e8ba8191..0f8a6685 100644 --- a/shared/plugins/reference/domains/backend.md +++ b/shared/plugins/reference/domains/backend.md @@ -147,7 +147,7 @@ Core 把中转的调用以 `lithe/function/invoke` 转给被调方。和任何 `run/start` 的参数: - `label`:1–256 个字符,不含控制字符,作为 Run 窗口条目的标题。 -- `process`:`{executable, arguments, workingDirectory, environment}`,四个字段都必填,未知字段被拒绝。`executable` 是 `{kind: "tool", tool}`(`tool` 是清单 `requiresTools` 列出的工具定义 ID,宿主按[工具链](toolchains.md)的分层解析)或 `{kind: "packaged", path}`(插件包内文件的规范化相对路径)。参数、工作目录(相对工作区根、且是其中已存在的目录)和环境的上限同[运行准备](../../contract/v1/README.md#provider-run-preparation)。 +- `process`:`{executable, arguments, workingDirectory, environment, outputEncoding?}`,前四个字段必填,未知字段被拒绝。`outputEncoding` 声明进程输出使用的字符编码(例如 `gbk`、`shift-jis`),宿主解码控制台的每一行时先试它,取值和别名同[运行准备](../../contract/v1/README.md#provider-run-preparation);宿主不能按行解码的编码(例如 `utf-16`)在 `process.outputEncoding` 被拒绝。不确定时不写,宿主按 UTF-8 和系统代码页判断。`executable` 是 `{kind: "tool", tool}`(`tool` 是清单 `requiresTools` 列出的工具定义 ID,宿主按[工具链](toolchains.md)的分层解析)或 `{kind: "packaged", path}`(插件包内文件的规范化相对路径)。参数、工作目录(相对工作区根、且是其中已存在的目录)和环境的上限同[运行准备](../../contract/v1/README.md#provider-run-preparation)。 - `temporaryFiles`:最多 4 个文件,每个最多 4 MiB。`{name, contents}` 是文本,宿主按 UTF-8 写入;`{name, base64}` 是标准 base64 字节,宿主原样写入,不转码,用于编码必须由插件决定的格式(例如按系统代码页读取参数文件的启动器)。两者都有或都没有时在 `temporaryFiles[]` 被拒绝。宿主在自己的临时目录写入,运行结束时删除,并把 `process.arguments` 和 `process.environment` 里的 `${temporaryFile:}` 替换成文件路径,插件不需要知道临时目录在哪。`name` 唯一,1–64 个字母、数字、`.`、`_`、`-`,以字母或数字开头。 - `debug`:`{configurationType, target}`,让这次运行成为调试会话,见[调试适配器](debug-adapters.md#由插件后端发起调试会话)。`configurationType` 是公开的调试适配器别名;`target` 是 `{kind: "connection", port}`(进程在 `port`,1–65535,监听调试器,由后端写进参数,宿主等待并附加适配器)或 `{kind: "launch"}`(适配器自己启动进程,按 `targetBindings` 从 `process` 取程序、参数、目录和环境)。 - `rerun`:`{function, data}`,插件已注册的函数和它的参数(最多 64 KiB 的 JSON 对象)。用户选“再次运行”时,宿主以 `data` 为参数、当前 `context` 调用该函数,后端再回答一次新的 `run/start`,所以重启由后端准备;没有 `rerun` 的条目不能再次运行。 @@ -367,7 +367,7 @@ Notification (the backend does not reply): `lithe/host/run/didExit` with `{runID `run/start` parameters: - `label`: 1 to 256 characters without control characters; it titles the Run window entry. -- `process`: `{executable, arguments, workingDirectory, environment}`, all four required; an unknown field is refused. `executable` is `{kind: "tool", tool}` (`tool` is a tool-definition ID that the manifest lists in `requiresTools`, which the host resolves through the layers described in [Toolchains](toolchains.md)) or `{kind: "packaged", path}` (a normalized relative path of a file inside the plugin package). Arguments, the working directory (relative to the workspace root and an existing directory inside it), and the environment have the bounds of [run preparation](../../contract/v1/README.md#provider-run-preparation). +- `process`: `{executable, arguments, workingDirectory, environment, outputEncoding?}`, the first four required; an unknown field is refused. `outputEncoding` declares the character encoding the process writes (for example `gbk` or `shift-jis`), which the host tries first for every console line; its values and aliases are those of [run preparation](../../contract/v1/README.md#provider-run-preparation). An encoding the host cannot decode lines in (for example `utf-16`) is refused at `process.outputEncoding`. Leave it out when unsure; the host then uses UTF-8, with GBK fallback on Windows. `executable` is `{kind: "tool", tool}` (`tool` is a tool-definition ID that the manifest lists in `requiresTools`, which the host resolves through the layers described in [Toolchains](toolchains.md)) or `{kind: "packaged", path}` (a normalized relative path of a file inside the plugin package). Arguments, the working directory (relative to the workspace root and an existing directory inside it), and the environment have the bounds of [run preparation](../../contract/v1/README.md#provider-run-preparation). - `temporaryFiles`: at most four files of up to 4 MiB each. `{name, contents}` is text the host writes as UTF-8; `{name, base64}` is bytes in standard base64 the host writes unchanged, without transcoding, for a format whose encoding the plugin must choose (such as a launcher that reads its argument file in the system code page). A file with both or neither is refused at `temporaryFiles[]`. The host writes them into its own temporary directory, removes them when the run ends, and replaces `${temporaryFile:}` in `process.arguments` and `process.environment` with the file's path, so the plugin never needs to know where the host keeps temporary files. A `name` is unique, 1 to 64 letters, digits, `.`, `_`, or `-`, and starts with a letter or digit. - `debug`: `{configurationType, target}`, which makes the run a debug session; see [Debug adapters](debug-adapters.md#starting-a-debug-session-from-a-plugin-backend). `configurationType` is a public debug adapter alias; `target` is `{kind: "connection", port}` (the process listens for a debugger on `port`, 1 to 65535, which the backend puts into the arguments; the host waits for it and attaches the adapter) or `{kind: "launch"}` (the adapter starts the process itself, taking program, arguments, directory, and environment from `process` through its `targetBindings`). - `rerun`: `{function, data}`, one of the plugin's registered functions and its params (a JSON object of up to 64 KiB). When the user chooses Run again, the host invokes the function with `data` as the params and the current `context`, and the backend answers with a new `run/start`, so the backend prepares the restart; without `rerun` the entry cannot be rerun. diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index f3b2d39b..2eb9a93d 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -16,6 +16,8 @@ - [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127),[@Mucheen](https://github.com/Mucheen),**API-25**:从 `grammar.path` 指定的 TextMate 语法或独立的 `grammars/.first-line.json` 读取可选 `firstLineMatch`。独立文件可沿用宿主现有高亮。旧桌面仍可安装 `languages: 0` 的同一插件包。Core 解码返回可选提示并匹配完整首行,既有路径与用户关联优先。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 +- [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-23、API-29):`run/start` 的 `process` 和提供者 `lithe/build/prepareRun` 的返回值新增可选 `outputEncoding`,用稳定编码 ID 或别名声明进程写入管道的编码;Core 校验并规范化,拒绝未知或不兼容 ASCII 的编码。用户固定编码优先;自动模式逐行尝试声明、UTF-8,以及仅 Windows 的 GBK。省略字段时所有平台默认 UTF-8,Windows 兼容 GBK;不修改进程环境或终端代码页。新增宿主内部 Core 命令 `outputEncoding.resolve`,返回同一解析规则的候选与可选编码列表,不是插件 RPC。见 [1lck/Lithe-IDEA#2186](https://github.com/1lck/Lithe-IDEA/issues/2186)。 + - [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112),[@Mucheen](https://github.com/Mucheen),**`buildSystems` 1**(API-29):清单新增 `buildSystems[].test.discoveryCommand`,已有测试运行可以独立采用命令或 provider。命令使用现有构建工具,把 `litheTestDiscovery` v0 写到宿主提供的 `${outputFile}`。Core 的 `build.testDiscoveryPlan`、`build.decodeTestDiscovery` 和测试树兼容两种发现来源,检查每条选择器可原样运行,命令尝试沿用 `lithe/build/discoverTests` 的结构化终态。没有新增宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 ## 按协议查首次出现 @@ -145,6 +147,8 @@ | — | `keymapImport/listInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | — | `keymapImport/readChunk` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-23 | `run/start`:`temporaryFiles` 增加 `{name, base64}` 字节文件 | 0 | 2026-11-13 | [#23](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/23) | +| API-23 | `run/start`:`process.outputEncoding` 可选声明 | 0 | 待合入 | [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128) | +| API-29 | `lithe/build/prepareRun`:返回值 `outputEncoding` 可选声明(提供者方法) | `litheBuild` 0、1 | 待合入 | [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128) | ## 时间线(新的在上)