Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 42 additions & 7 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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 |
Expand Down
1 change: 1 addition & 0 deletions rust/crates/build/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
17 changes: 17 additions & 0 deletions rust/crates/build/src/run_preparation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<&'static str>, ()> {
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<Value> {
let invalid = || decode::invalid_output("Invalid provider process preparation result.");
Expand Down
23 changes: 21 additions & 2 deletions rust/crates/build/src/run_start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -168,6 +184,9 @@ fn decode_start(payload: &DecodeStartPayload, required_tools: &[String]) -> Vali
})
.collect::<Vec<_>>(),
});
if let Some(encoding) = output_encoding {
start["outputEncoding"] = json!(encoding);
}
if let Some(debug) = &params.debug {
start["debug"] = start_debug(debug)?;
}
Expand Down
6 changes: 6 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)),
Expand Down Expand Up @@ -1860,6 +1865,7 @@ mod tests {
"outputLinks.match",
"outputLinks.decodeResolution",
"outputStyle.decode",
"outputEncoding.resolve",
] {
assert!(CoreCommand::parse(command).is_some(), "missing {command}");
}
Expand Down
16 changes: 16 additions & 0 deletions rust/crates/core/src/runtime/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<lithe_terminal::OutputEncodingPolicy>(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::<MarkdownRenderRequest>(parsed.payload).map_err(|error| {
CoreError::new(ErrorCode::InvalidRequest, "Invalid Markdown render request")
Expand Down
8 changes: 8 additions & 0 deletions rust/crates/core/src/tests/build_systems.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"])),
Expand Down
59 changes: 59 additions & 0 deletions rust/crates/core/src/tests/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8> {
(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(
Expand Down
4 changes: 3 additions & 1 deletion rust/crates/terminal/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }

Expand Down
Loading
Loading