返回 CodeWhale
osc8.rs
根目录 / crates / tui-kit / src / osc8.rs
1 //! OSC 8 hyperlink emission and stripping.
2 //!
3 //! Modern terminals (iTerm2, Terminal.app 13+, Ghostty, Kitty, WezTerm,
4 //! Alacritty, recent gnome-terminal/konsole) make a substring clickable when
5 //! it is wrapped in:
6 //!
7 //! ```text
8 //! \x1b]8;;TARGET\x1b\\LABEL\x1b]8;;\x1b\\
9 //! ```
10 //!
11 //! Terminals that don't understand the sequence simply render the visible
12 //! `LABEL` and ignore the escape. So emitting OSC 8 is a strict UX upgrade for
13 //! supporting terminals and a no-op for the rest.
14 //!
15 //! # Architecture (#3029)
16 //!
17 //! Link targets never enter `Span::content` or a ratatui `Buffer`. Markdown
18 //! wrapping produces plain visible spans plus parallel [`LineLink`] metadata.
19 //! Transcript surfaces translate those relative columns into absolute
20 //! [`LinkRegion`]s for the current viewport. `ColorCompatBackend::draw` then
21 //! emits OSC 8 escapes around the corresponding cell runs. This keeps text
22 //! layout, selection, and clipboard extraction byte-for-byte identical with
23 //! links enabled or disabled, including long links wrapped across rows.
24 //! Markdown contributes only normalized HTTP(S) and absolute `file://`
25 //! targets, and emission percent-encodes terminal control characters as
26 //! defense in depth.
27 //!
28 //! Opening is terminal-owned: supporting terminals conventionally use
29 //! Cmd-click on macOS or Ctrl-click on Linux/Windows. CodeWhale does not
30 //! intercept those gestures or launch URLs itself, so mouse selection remains
31 //! independent of browser-opening policy.
32 //!
33 //! The clipboard/selection extraction path still strips any residual codes via
34 //! [`strip_into`] / [`strip_ansi_into`] as a defense-in-depth.
35
36 use std::sync::atomic::{AtomicBool, Ordering};
37
38 const OSC8_PREFIX: &str = "\x1b]8;;";
39 const OSC8_TERMINATOR: &str = "\x1b\\";
40 const OSC8_CLOSE: &str = "\x1b]8;;\x1b\\";
41
42 /// A contiguous run of cells on one terminal row that share a hyperlink target.
43 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub struct LinkRegion {
45 pub row: u16,
46 pub col_start: u16,
47 pub col_end: u16,
48 pub target: String,
49 }
50
51 /// Hyperlink metadata for one already-wrapped visible line. Columns are
52 /// zero-based display columns relative to that line and `col_end` is
53 /// inclusive, matching [`LinkRegion`].
54 #[derive(Debug, Clone, PartialEq, Eq)]
55 pub struct LineLink {
56 pub col_start: usize,
57 pub col_end: usize,
58 pub target: String,
59 pub line: Option<u32>,
60 }
61
62 impl LineLink {
63 #[must_use]
64 pub fn shifted(&self, columns: usize) -> Self {
65 Self {
66 col_start: self.col_start.saturating_add(columns),
67 col_end: self.col_end.saturating_add(columns),
68 target: self.target.clone(),
69 line: self.line,
70 }
71 }
72 }
73
74 /// Translate per-line relative metadata into absolute terminal regions for a
75 /// rendered viewport. Metadata outside `area` is clipped rather than allowed
76 /// to hyperlink adjacent chrome (for example the transcript scrollbar).
77 #[must_use]
78 #[cfg(any(test, feature = "test-support"))]
79 pub fn link_regions_for_lines(
80 area: ratatui::layout::Rect,
81 links: &[Vec<LineLink>],
82 ) -> Vec<LinkRegion> {
83 link_regions_for_plan(
84 &codewhale_ratatui::TranscriptViewport::new(&[]).plan(area),
85 links,
86 )
87 }
88
89 /// Project targets through the final painted geometry; no target enters kit data.
90 #[must_use]
91 pub fn link_regions_for_plan(
92 plan: &codewhale_ratatui::TranscriptViewportPlan,
93 links: &[Vec<LineLink>],
94 ) -> Vec<LinkRegion> {
95 let mut regions = Vec::new();
96 for (row, links) in links.iter().take(usize::from(plan.area.height)).enumerate() {
97 for link in links {
98 for rect in plan.link_rects(row, link.col_start, link.col_end) {
99 regions.push(LinkRegion {
100 row: rect.y,
101 col_start: rect.x,
102 col_end: rect.right().saturating_sub(1),
103 target: link.target.clone(),
104 });
105 }
106 }
107 }
108 regions
109 }
110
111 pub const MAX_OSC8_TARGET_BYTES: usize = 8192;
112
113 #[must_use]
114 pub fn target_within_limit(target: &str) -> bool {
115 let mut len = 0usize;
116 for ch in target.chars() {
117 len += if ch.is_control() {
118 ch.len_utf8() * 3
119 } else {
120 ch.len_utf8()
121 };
122 if len > MAX_OSC8_TARGET_BYTES {
123 return false;
124 }
125 }
126 true
127 }
128
129 /// Write an OSC 8 hyperlink open sequence for `target` to `w`.
130 pub fn write_osc8_open(w: &mut impl std::io::Write, target: &str) -> std::io::Result<()> {
131 if !target_within_limit(target) {
132 return Ok(());
133 }
134 w.write_all(OSC8_PREFIX.as_bytes())?;
135 write_sanitized_target(w, target)?;
136 w.write_all(OSC8_TERMINATOR.as_bytes())
137 }
138
139 /// Percent-encode terminal control characters before they enter an OSC
140 /// parameter. Markdown and restored transcripts are untrusted input: a raw
141 /// BEL, ESC/ST, or other control byte could terminate the link and inject an
142 /// arbitrary terminal sequence. Printable Unicode and ordinary URL bytes are
143 /// preserved byte-for-byte.
144 fn write_sanitized_target(w: &mut impl std::io::Write, target: &str) -> std::io::Result<()> {
145 const HEX: &[u8; 16] = b"0123456789ABCDEF";
146 let mut encoded = [0u8; 4];
147 for ch in target.chars() {
148 let value = ch.encode_utf8(&mut encoded);
149 if ch.is_control() {
150 for &byte in value.as_bytes() {
151 w.write_all(&[
152 b'%',
153 HEX[usize::from(byte >> 4)],
154 HEX[usize::from(byte & 0x0f)],
155 ])?;
156 }
157 } else {
158 w.write_all(value.as_bytes())?;
159 }
160 }
161 Ok(())
162 }
163
164 /// Write an OSC 8 hyperlink close sequence to `w`.
165 pub fn write_osc8_close(w: &mut impl std::io::Write) -> std::io::Result<()> {
166 w.write_all(OSC8_CLOSE.as_bytes())
167 }
168
169 /// Process-wide enable flag. Set once at app init from `[tui] osc8_links`
170 /// (when present); otherwise defaults to on for macOS/Linux and off for
171 /// Windows legacy consoles (see `ui.rs`'s `osc8_default_on`). Read by the
172 /// renderer to gate out-of-band OSC 8 emission.
173 static ENABLED: AtomicBool = AtomicBool::new(true);
174
175 /// Set the process-wide OSC 8 enable flag. Intended to be called once at
176 /// startup; subsequent calls take effect immediately.
177 pub fn set_enabled(enabled: bool) {
178 ENABLED.store(enabled, Ordering::Relaxed);
179 }
180
181 /// Whether OSC 8 hyperlink emission is currently enabled.
182 #[must_use]
183 pub fn enabled() -> bool {
184 ENABLED.load(Ordering::Relaxed)
185 }
186
187 // --- Thread-local link region accumulator (#3029) ---
188
189 use std::cell::RefCell;
190
191 thread_local! {
192 /// Link regions collected during the current render frame.
193 /// Populated by transcript widgets from their parallel line metadata;
194 /// consumed and cleared by `ColorCompatBackend::draw()`.
195 pub static FRAME_LINKS: RefCell<Vec<LinkRegion>> = const { RefCell::new(Vec::new()) };
196 }
197
198 /// Replace the thread-local frame link buffer with `links`.
199 pub fn set_frame_links(links: Vec<LinkRegion>) {
200 FRAME_LINKS.with(|cell| {
201 *cell.borrow_mut() = links;
202 });
203 }
204
205 /// Append `links` to the thread-local frame link buffer. Used when more than
206 /// one widget renders link-bearing content into the same frame (e.g. the main
207 /// transcript and the live-transcript overlay): each seam appends rather than
208 /// replacing, so all regions reach `ColorCompatBackend::draw`.
209 pub fn append_frame_links(links: Vec<LinkRegion>) {
210 FRAME_LINKS.with(|cell| cell.borrow_mut().extend(links));
211 }
212
213 /// Replace the portion of the current frame-link map covered by an opaque
214 /// overlay, preserving (and clipping) regions that remain visible around it.
215 /// This prevents a transcript URL underneath a modal from making unrelated
216 /// popup text clickable when both widgets paint in the same terminal frame.
217 pub fn overlay_frame_links(area: ratatui::layout::Rect, links: Vec<LinkRegion>) {
218 if area.width == 0 || area.height == 0 {
219 append_frame_links(links);
220 return;
221 }
222 let x_start = area.x;
223 let x_end = area.right();
224 let y_start = area.y;
225 let y_end = area.bottom();
226 FRAME_LINKS.with(|cell| {
227 let mut current = cell.borrow_mut();
228 let mut visible = Vec::with_capacity(current.len().saturating_add(links.len()));
229 for region in current.drain(..) {
230 if region.row < y_start
231 || region.row >= y_end
232 || region.col_end < x_start
233 || region.col_start >= x_end
234 {
235 visible.push(region);
236 continue;
237 }
238 if region.col_start < x_start {
239 let mut left = region.clone();
240 left.col_end = x_start.saturating_sub(1);
241 visible.push(left);
242 }
243 if region.col_end >= x_end {
244 let mut right = region;
245 right.col_start = x_end;
246 visible.push(right);
247 }
248 }
249 visible.extend(links);
250 *current = visible;
251 });
252 }
253
254 /// Take the thread-local frame links, leaving an empty vec behind.
255 pub fn take_frame_links() -> Vec<LinkRegion> {
256 FRAME_LINKS.with(|cell| std::mem::take(&mut *cell.borrow_mut()))
257 }
258
259 /// Strip ANSI/OSC/control sequences from `s` into `out`.
260 ///
261 /// Delegates to the single shared implementation in
262 /// [`codewhale_sanitize::sanitize`] (FEAT-025 D4) so `/export`, `/structcopy`,
263 /// and the renderer cannot drift.
264 pub fn strip_ansi_into(s: &str, out: &mut String) {
265 codewhale_sanitize::sanitize::strip_ansi_into(s, out);
266 }
267
268 /// Like [`strip_ansi_into`], but SGR sequences (`ESC [ … m`: colour, bold,
269 /// underline, reset) pass through untouched so a renderer that understands
270 /// them can paint the output as the tool emitted it. Everything else — OSC
271 /// (including OSC 8 hyperlink wrappers), cursor movement, DCS, lone control
272 /// bytes — is still removed; only the styling survives.
273 pub fn strip_ansi_keep_sgr_into(s: &str, out: &mut String) {
274 codewhale_sanitize::sanitize::strip_ansi_keep_sgr_into(s, out);
275 }
276
277 /// Length in bytes of the UTF-8 sequence that starts with `lead`. Falls back
278 /// to `1` for continuation bytes / invalid leads so callers always make
279 /// forward progress.
280 ///
281 /// Delegates to the shared implementation in [`codewhale_sanitize::sanitize`].
282 fn utf8_seq_len(lead: u8) -> usize {
283 codewhale_sanitize::sanitize::utf8_seq_len(lead)
284 }
285
286 /// Strip OSC 8 escape sequences from `s` into `out`, preserving the visible
287 /// label text. Other escapes (color, style) pass through untouched. The
288 /// implementation handles both the standard `ESC \` and the lone `BEL`
289 /// terminators that some emitters use.
290 pub fn strip_into(s: &str, out: &mut String) {
291 let bytes = s.as_bytes();
292 let mut i = 0;
293 while i < bytes.len() {
294 // Look for the OSC 8 prefix `ESC ] 8 ;`
295 if i + 4 <= bytes.len()
296 && bytes[i] == 0x1b
297 && bytes[i + 1] == b']'
298 && bytes[i + 2] == b'8'
299 && bytes[i + 3] == b';'
300 {
301 // Skip until the string terminator (ESC \) or BEL.
302 let mut j = i + 4;
303 while j < bytes.len() {
304 if bytes[j] == 0x07 {
305 j += 1;
306 break;
307 }
308 if bytes[j] == 0x1b && j + 1 < bytes.len() && bytes[j + 1] == b'\\' {
309 j += 2;
310 break;
311 }
312 j += 1;
313 }
314 i = j;
315 continue;
316 }
317 let b = bytes[i];
318 if b < 0x80 {
319 out.push(b as char);
320 i += 1;
321 } else {
322 let len = utf8_seq_len(b);
323 let end = (i + len).min(bytes.len());
324 if let Ok(chunk) = std::str::from_utf8(&bytes[i..end]) {
325 out.push_str(chunk);
326 }
327 i = end;
328 }
329 }
330 }
331
332 #[cfg(test)]
333 mod tests {
334 use super::*;
335 use std::sync::Mutex;
336
337 /// Serialize tests that read or write the `ENABLED` flag so they don't
338 /// race each other under cargo's default parallel test runner.
339 static FLAG_GUARD: Mutex<()> = Mutex::new(());
340
341 fn strip(s: &str) -> String {
342 let mut out = String::with_capacity(s.len());
343 strip_into(s, &mut out);
344 out
345 }
346
347 fn wrapped_link(target: &str, label: &str) -> String {
348 format!("{OSC8_PREFIX}{target}{OSC8_TERMINATOR}{label}{OSC8_CLOSE}")
349 }
350
351 #[test]
352 fn wrapped_link_fixture_is_osc_8_compliant() {
353 let wrapped = wrapped_link("https://example.com", "click me");
354 assert_eq!(
355 wrapped,
356 "\x1b]8;;https://example.com\x1b\\click me\x1b]8;;\x1b\\"
357 );
358 }
359
360 #[test]
361 fn strip_removes_wrapper_keeps_label() {
362 let wrapped = wrapped_link("https://example.com", "click me");
363 assert_eq!(strip(&wrapped), "click me");
364 }
365
366 #[test]
367 fn strip_handles_bel_terminator() {
368 let wrapped = "\x1b]8;;https://example.com\x07click me\x1b]8;;\x07";
369 assert_eq!(strip(wrapped), "click me");
370 }
371
372 #[test]
373 fn strip_passes_through_text_with_no_escapes() {
374 let plain = "no escapes here";
375 assert_eq!(strip(plain), plain);
376 }
377
378 #[test]
379 fn strip_preserves_non_osc_8_escapes() {
380 // Color escape stays in place; only OSC 8 wrappers are removed.
381 let mixed = format!(
382 "\x1b[31mred\x1b[0m {wrapped}",
383 wrapped = wrapped_link("https://example.com", "click")
384 );
385 assert_eq!(strip(&mixed), "\x1b[31mred\x1b[0m click");
386 }
387
388 fn strip_ansi(s: &str) -> String {
389 let mut out = String::with_capacity(s.len());
390 strip_ansi_into(s, &mut out);
391 out
392 }
393
394 #[test]
395 fn strip_ansi_removes_csi_sgr_and_keeps_text() {
396 let coloured = "526 \x1b[1;32mOPEN\x1b[0m bug fix";
397 assert_eq!(strip_ansi(coloured), "526 OPEN bug fix");
398 }
399
400 #[test]
401 fn strip_keep_sgr_keeps_colour_and_drops_everything_else() {
402 let mut out = String::new();
403 strip_ansi_keep_sgr_into(
404 "\x1b]8;;https://x\x07\x1b[1;32mok\x1b[0m\x1b]8;;\x07\x1b[2K\x1b[?25l tail",
405 &mut out,
406 );
407 assert_eq!(out, "\x1b[1;32mok\x1b[0m tail");
408 let mut plain = String::new();
409 strip_ansi_into(&out, &mut plain);
410 assert_eq!(plain, "ok tail");
411 }
412
413 #[test]
414 fn strip_ansi_removes_osc_8_wrapper() {
415 let wrapped = wrapped_link("https://example.com", "click");
416 assert_eq!(strip_ansi(&wrapped), "click");
417 }
418
419 #[test]
420 fn strip_ansi_preserves_newlines_tabs_and_cr() {
421 let s = "a\nb\tc\rd";
422 assert_eq!(strip_ansi(s), "a\nb\tc\rd");
423 }
424
425 #[test]
426 fn strip_ansi_drops_lone_control_bytes() {
427 // Bare BEL or other C0 control bytes that aren't \n/\r/\t are dropped
428 // so they can't paint as visible cells.
429 let s = "a\x07b\x01c";
430 assert_eq!(strip_ansi(s), "abc");
431 }
432
433 #[test]
434 fn strip_ansi_preserves_utf8_multibyte_chars() {
435 // CJK, accented Latin, and emoji must survive the strip without being
436 // re-decoded as Latin-1 (which would explode 你 -> ä½ ).
437 let s = "Phase 1: 第一步 README é 🚀";
438 assert_eq!(strip_ansi(s), "Phase 1: 第一步 README é 🚀");
439
440 let coloured = "\x1b[1;32m第一步\x1b[0m done";
441 assert_eq!(strip_ansi(coloured), "第一步 done");
442 }
443
444 #[test]
445 fn strip_preserves_utf8_multibyte_chars() {
446 let wrapped = wrapped_link("https://example.com", "点击我");
447 assert_eq!(strip(&wrapped), "点击我");
448 }
449
450 #[test]
451 fn open_sequence_percent_encodes_target_control_injection() {
452 let target = "https://safe.test/a\x07b\x1b]8;;https://evil.test\x1b\\c\x7f\u{009c}";
453 let mut bytes = Vec::new();
454 write_osc8_open(&mut bytes, target).expect("write OSC 8 open");
455 let rendered = String::from_utf8(bytes.clone()).expect("valid UTF-8 output");
456
457 assert_eq!(rendered.matches(OSC8_PREFIX).count(), 1, "{rendered:?}");
458 assert_eq!(rendered.matches(OSC8_TERMINATOR).count(), 1, "{rendered:?}");
459 assert_eq!(bytes.iter().filter(|byte| **byte == 0x1b).count(), 2);
460 assert!(!bytes.contains(&0x07), "BEL escaped: {rendered:?}");
461 assert!(!bytes.contains(&0x7f), "DEL escaped: {rendered:?}");
462 assert!(
463 rendered.contains("a%07b%1B]8;;https://evil.test%1B\\c%7F%C2%9C"),
464 "control bytes must be percent-encoded: {rendered:?}"
465 );
466 }
467
468 #[test]
469 fn open_sequence_caps_target_at_max_osc8_target_bytes() {
470 let exact = "a".repeat(MAX_OSC8_TARGET_BYTES);
471 assert!(target_within_limit(&exact));
472 let mut exact_bytes = Vec::new();
473 write_osc8_open(&mut exact_bytes, &exact).expect("write exact-limit OSC 8");
474 assert!(!exact_bytes.is_empty());
475
476 let too_long = "a".repeat(MAX_OSC8_TARGET_BYTES + 1);
477 assert!(!target_within_limit(&too_long));
478 let mut dropped = Vec::new();
479 write_osc8_open(&mut dropped, &too_long).expect("drop oversized OSC 8");
480 assert!(dropped.is_empty());
481
482 let expanded_over = format!("{}\x07", "a".repeat(MAX_OSC8_TARGET_BYTES - 2));
483 assert!(!target_within_limit(&expanded_over));
484 let mut dropped_expanded = Vec::new();
485 write_osc8_open(&mut dropped_expanded, &expanded_over)
486 .expect("drop percent-expanded oversized OSC 8");
487 assert!(dropped_expanded.is_empty());
488 }
489
490 #[test]
491 fn enabled_is_true_by_default_when_untouched() {
492 // Hold the flag guard so we observe the initial state, not a value
493 // mid-flight from `set_enabled_round_trips`. The flag *defaults* to
494 // true at static init and tests in this module are the only writers.
495 let _g = FLAG_GUARD.lock().unwrap_or_else(|e| e.into_inner());
496 assert!(enabled());
497 }
498
499 #[test]
500 fn set_enabled_round_trips() {
501 let _g = FLAG_GUARD.lock().unwrap_or_else(|e| e.into_inner());
502 let prior = enabled();
503 set_enabled(false);
504 assert!(!enabled());
505 set_enabled(true);
506 assert!(enabled());
507 set_enabled(prior);
508 }
509
510 #[test]
511 fn line_links_translate_to_absolute_clipped_regions() {
512 let area = ratatui::layout::Rect::new(7, 3, 8, 2);
513 let links = vec![
514 vec![
515 LineLink {
516 col_start: 2,
517 col_end: 20,
518 target: "https://example.test/long".to_string(),
519 line: None,
520 },
521 LineLink {
522 col_start: 8,
523 col_end: 9,
524 target: "outside".to_string(),
525 line: None,
526 },
527 ],
528 vec![LineLink {
529 col_start: 0,
530 col_end: 1,
531 target: "https://example.test/next".to_string(),
532 line: None,
533 }],
534 vec![LineLink {
535 col_start: 0,
536 col_end: 0,
537 target: "below viewport".to_string(),
538 line: None,
539 }],
540 ];
541
542 assert_eq!(
543 link_regions_for_lines(area, &links),
544 vec![
545 LinkRegion {
546 row: 3,
547 col_start: 9,
548 col_end: 14,
549 target: "https://example.test/long".to_string(),
550 },
551 LinkRegion {
552 row: 4,
553 col_start: 7,
554 col_end: 8,
555 target: "https://example.test/next".to_string(),
556 },
557 ]
558 );
559 }
560
561 #[test]
562 fn opaque_overlay_replaces_and_clips_underlying_regions() {
563 set_frame_links(vec![
564 LinkRegion {
565 row: 4,
566 col_start: 0,
567 col_end: 20,
568 target: "under-wide".to_string(),
569 },
570 LinkRegion {
571 row: 5,
572 col_start: 6,
573 col_end: 8,
574 target: "under-covered".to_string(),
575 },
576 ]);
577 overlay_frame_links(
578 ratatui::layout::Rect::new(5, 4, 10, 2),
579 vec![LinkRegion {
580 row: 4,
581 col_start: 7,
582 col_end: 8,
583 target: "modal".to_string(),
584 }],
585 );
586
587 assert_eq!(
588 take_frame_links(),
589 vec![
590 LinkRegion {
591 row: 4,
592 col_start: 0,
593 col_end: 4,
594 target: "under-wide".to_string(),
595 },
596 LinkRegion {
597 row: 4,
598 col_start: 15,
599 col_end: 20,
600 target: "under-wide".to_string(),
601 },
602 LinkRegion {
603 row: 4,
604 col_start: 7,
605 col_end: 8,
606 target: "modal".to_string(),
607 },
608 ]
609 );
610 }
611 }
612
612 lines RUST