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
243 changes: 184 additions & 59 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Write as _, sync::Arc};

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
AnyElement, App, ContentMask, Hsla, IntoElement as _, ParentElement as _, Rgba, Styled as _,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use gpui_base::ElementExt as _;
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;
use crate::theme::{ActiveTheme as _, HighlightTheme};

const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;
Expand DownExpand Up@@ -61,10 +60,26 @@ impl CommandPanelCache {
}
}

#[derive(Clone)]
struct CommandTheme {
foreground: Hsla,
background: Hsla,
highlight_theme: Arc<HighlightTheme>,
}

impl CommandTheme {
fn matches(&self, other: &Self) -> bool {
self.foreground == other.foreground
&& self.background == other.background
&& Arc::ptr_eq(&self.highlight_theme, &other.highlight_theme)
}
}

struct CachedPanel {
command: String,
displayed_command: String,
command_snapshot: TermSnapshot,
command_rows: usize,
command_theme: Option<CommandTheme>,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
Expand All@@ -80,13 +95,14 @@ impl CachedPanel {
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let (command_snapshot, command_rows) = command_snapshot(command, cols, None);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
displayed_command,
command_snapshot,
command_rows,
command_theme: None,
cols,
output_emulator,
output: Vec::new(),
Expand All@@ -102,7 +118,8 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(command, self.cols, self.command_theme.as_ref());
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -127,7 +144,8 @@ impl CachedPanel {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, cols, self.command_theme.as_ref());
let output = self.output.clone();
self.rebuild_output(&output);
true
Expand DownExpand Up@@ -164,30 +182,37 @@ impl CachedPanel {
);
}

fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
fn update_command_theme(&mut self, command_theme: CommandTheme) {
if self
.command_theme
.as_ref()
.is_some_and(|cached| cached.matches(&command_theme))
{
return;
}
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, self.cols, Some(&command_theme));
self.command_theme = Some(command_theme);
}

fn render(&mut self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let command_theme = CommandTheme {
foreground: cx.theme().foreground,
background: cx.theme().background,
highlight_theme: cx.theme().highlight_theme.clone(),
};
self.update_command_theme(command_theme);
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
let command = grid_element(
&self.command_snapshot,
self.command_rows,
self.cols,
palette,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
Expand DownExpand Up@@ -242,41 +267,93 @@ fn grid_element(
.into_any_element()
}

fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
fn command_snapshot(
command: &str,
cols: usize,
command_theme: Option<&CommandTheme>,
) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(cols, MAX_COMMAND_ROWS);
let command = clamp_command(command, cols);
if let Some(command_theme) = command_theme {
emulator.feed(highlighted_command(&command, command_theme).as_bytes());
} else {
emulator.feed(command.as_bytes());
}
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn highlighted_command(command: &str, theme: &CommandTheme) -> String {
let highlights = highlight::highlight_source(command, "bash", &theme.highlight_theme);
let mut highlighted = String::new();
let mut cursor = 0;
for (range, style) in highlights {
if range.start > cursor {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..range.start]);
}
push_command_color(
&mut highlighted,
style.color.unwrap_or(theme.foreground),
theme.background,
);
highlighted.push_str(&command[range.clone()]);
cursor = range.end;
}
if cursor < command.len() {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..]);
}
highlighted
}

fn push_command_color(command: &mut String, foreground: Hsla, background: Hsla) {
let (r, g, b) = faded_command_rgb(foreground, background);
let _ = write!(command, "\x1b[38;2;{r};{g};{b}m");
}

fn faded_command_rgb(foreground: Hsla, background: Hsla) -> (u8, u8, u8) {
let faded = Rgba::from(background).blend(Rgba::from(foreground).opacity(0.7));
(
(faded.r * 255.) as u8,
(faded.g * 255.) as u8,
(faded.b * 255.) as u8,
)
}

fn clamp_command(command: &str, cols: usize) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
break;
}
lines.push(String::new());
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
if col == cols {
row += 1;
col = 0;
}
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == cols && chars.peek().is_some() {
result.push('…');
break;
}
last.push('…');
result.push(ch);
col += 1;
}
let rows = lines.len();
(lines.join("\n"), rows)
result
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -313,6 +390,14 @@ mod tests {
}
}

fn dark_command_theme() -> CommandTheme {
CommandTheme {
foreground: rgb(0xffffff).into(),
background: rgb(0x000000).into(),
highlight_theme: HighlightTheme::default_dark(),
}
}

#[test]
fn ansi_output_uses_terminal_green() {
let panel = CachedPanel::new("echo green", "\x1b[32mgreen\x1b[0m");
Expand All@@ -330,13 +415,53 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
let mut panel = CachedPanel::new(&"x".repeat(DEFAULT_COLS * MAX_COMMAND_ROWS + 1), "");
panel.update_command_theme(dark_command_theme());
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, DEFAULT_COLS - 1)
.is_some_and(|text| text == "…")
);
}

#[test]
fn command_highlight_is_faded_truecolor_in_terminal_cells() {
let command = "if true; then echo yes; fi";
let command_theme = dark_command_theme();
let clamped = clamp_command(command, DEFAULT_COLS);
let raw_keyword_color =
highlight::highlight_source(&clamped, "bash", &command_theme.highlight_theme)
.into_iter()
.find_map(|(range, style)| {
clamped[range]
.contains("if")
.then_some(style.color)
.flatten()
})
.expect("bash keyword highlight color");
let expected = faded_command_rgb(raw_keyword_color, command_theme.background);

let mut panel = CachedPanel::new(command, "");
panel.update_command_theme(command_theme);
let paint = layout_grid(
&panel.command_snapshot,
palette(),
false,
None,
false,
false,
);
let command = paint
.text_runs
.iter()
.find(|run| run.text.contains("if"))
.expect("highlighted command run");
let AnsiColor::Spec(color) = command.style.fg else {
panic!("command keyword should use truecolor foreground");
};
assert_eq!((color.r, color.g, color.b), expected);
}

#[test]
Expand Down
16 changes: 11 additions & 5 deletions crates/ui/src/chat/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1070,11 +1070,17 @@ impl ChatView {
command, output, ..
}) => {
let panel_id = entry.id.clone();
let on_cols_change = cx.listener(move |this, cols: &usize, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, *cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
let on_cols_change = cx.listener(move |_this, cols: &usize, window, cx| {
// Fires from `on_prepaint`, i.e. while `List` holds its state
// borrowed; remeasuring inline would panic. Defer past the frame.
let cols = *cols;
let panel_id = panel_id.clone();
cx.defer_in(window, move |this, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
});
});
Some(self.command_panels.borrow_mut().render(
&entry.id,
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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
243 changes: 184 additions & 59 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Write as _, sync::Arc};

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
AnyElement, App, ContentMask, Hsla, IntoElement as _, ParentElement as _, Rgba, Styled as _,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use gpui_base::ElementExt as _;
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;
use crate::theme::{ActiveTheme as _, HighlightTheme};

const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;
Expand DownExpand Up@@ -61,10 +60,26 @@ impl CommandPanelCache {
}
}

#[derive(Clone)]
struct CommandTheme {
foreground: Hsla,
background: Hsla,
highlight_theme: Arc<HighlightTheme>,
}

impl CommandTheme {
fn matches(&self, other: &Self) -> bool {
self.foreground == other.foreground
&& self.background == other.background
&& Arc::ptr_eq(&self.highlight_theme, &other.highlight_theme)
}
}

struct CachedPanel {
command: String,
displayed_command: String,
command_snapshot: TermSnapshot,
command_rows: usize,
command_theme: Option<CommandTheme>,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
Expand All@@ -80,13 +95,14 @@ impl CachedPanel {
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let (command_snapshot, command_rows) = command_snapshot(command, cols, None);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
displayed_command,
command_snapshot,
command_rows,
command_theme: None,
cols,
output_emulator,
output: Vec::new(),
Expand All@@ -102,7 +118,8 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(command, self.cols, self.command_theme.as_ref());
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -127,7 +144,8 @@ impl CachedPanel {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, cols, self.command_theme.as_ref());
let output = self.output.clone();
self.rebuild_output(&output);
true
Expand DownExpand Up@@ -164,30 +182,37 @@ impl CachedPanel {
);
}

fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
fn update_command_theme(&mut self, command_theme: CommandTheme) {
if self
.command_theme
.as_ref()
.is_some_and(|cached| cached.matches(&command_theme))
{
return;
}
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, self.cols, Some(&command_theme));
self.command_theme = Some(command_theme);
}

fn render(&mut self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let command_theme = CommandTheme {
foreground: cx.theme().foreground,
background: cx.theme().background,
highlight_theme: cx.theme().highlight_theme.clone(),
};
self.update_command_theme(command_theme);
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
let command = grid_element(
&self.command_snapshot,
self.command_rows,
self.cols,
palette,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
Expand DownExpand Up@@ -242,41 +267,93 @@ fn grid_element(
.into_any_element()
}

fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
fn command_snapshot(
command: &str,
cols: usize,
command_theme: Option<&CommandTheme>,
) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(cols, MAX_COMMAND_ROWS);
let command = clamp_command(command, cols);
if let Some(command_theme) = command_theme {
emulator.feed(highlighted_command(&command, command_theme).as_bytes());
} else {
emulator.feed(command.as_bytes());
}
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn highlighted_command(command: &str, theme: &CommandTheme) -> String {
let highlights = highlight::highlight_source(command, "bash", &theme.highlight_theme);
let mut highlighted = String::new();
let mut cursor = 0;
for (range, style) in highlights {
if range.start > cursor {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..range.start]);
}
push_command_color(
&mut highlighted,
style.color.unwrap_or(theme.foreground),
theme.background,
);
highlighted.push_str(&command[range.clone()]);
cursor = range.end;
}
if cursor < command.len() {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..]);
}
highlighted
}

fn push_command_color(command: &mut String, foreground: Hsla, background: Hsla) {
let (r, g, b) = faded_command_rgb(foreground, background);
let _ = write!(command, "\x1b[38;2;{r};{g};{b}m");
}

fn faded_command_rgb(foreground: Hsla, background: Hsla) -> (u8, u8, u8) {
let faded = Rgba::from(background).blend(Rgba::from(foreground).opacity(0.7));
(
(faded.r * 255.) as u8,
(faded.g * 255.) as u8,
(faded.b * 255.) as u8,
)
}

fn clamp_command(command: &str, cols: usize) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
break;
}
lines.push(String::new());
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
if col == cols {
row += 1;
col = 0;
}
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == cols && chars.peek().is_some() {
result.push('…');
break;
}
last.push('…');
result.push(ch);
col += 1;
}
let rows = lines.len();
(lines.join("\n"), rows)
result
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -313,6 +390,14 @@ mod tests {
}
}

fn dark_command_theme() -> CommandTheme {
CommandTheme {
foreground: rgb(0xffffff).into(),
background: rgb(0x000000).into(),
highlight_theme: HighlightTheme::default_dark(),
}
}

#[test]
fn ansi_output_uses_terminal_green() {
let panel = CachedPanel::new("echo green", "\x1b[32mgreen\x1b[0m");
Expand All@@ -330,13 +415,53 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
let mut panel = CachedPanel::new(&"x".repeat(DEFAULT_COLS * MAX_COMMAND_ROWS + 1), "");
panel.update_command_theme(dark_command_theme());
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, DEFAULT_COLS - 1)
.is_some_and(|text| text == "…")
);
}

#[test]
fn command_highlight_is_faded_truecolor_in_terminal_cells() {
let command = "if true; then echo yes; fi";
let command_theme = dark_command_theme();
let clamped = clamp_command(command, DEFAULT_COLS);
let raw_keyword_color =
highlight::highlight_source(&clamped, "bash", &command_theme.highlight_theme)
.into_iter()
.find_map(|(range, style)| {
clamped[range]
.contains("if")
.then_some(style.color)
.flatten()
})
.expect("bash keyword highlight color");
let expected = faded_command_rgb(raw_keyword_color, command_theme.background);

let mut panel = CachedPanel::new(command, "");
panel.update_command_theme(command_theme);
let paint = layout_grid(
&panel.command_snapshot,
palette(),
false,
None,
false,
false,
);
let command = paint
.text_runs
.iter()
.find(|run| run.text.contains("if"))
.expect("highlighted command run");
let AnsiColor::Spec(color) = command.style.fg else {
panic!("command keyword should use truecolor foreground");
};
assert_eq!((color.r, color.g, color.b), expected);
}

#[test]
Expand Down
16 changes: 11 additions & 5 deletions crates/ui/src/chat/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1070,11 +1070,17 @@ impl ChatView {
command, output, ..
}) => {
let panel_id = entry.id.clone();
let on_cols_change = cx.listener(move |this, cols: &usize, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, *cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
let on_cols_change = cx.listener(move |_this, cols: &usize, window, cx| {
// Fires from `on_prepaint`, i.e. while `List` holds its state
// borrowed; remeasuring inline would panic. Defer past the frame.
let cols = *cols;
let panel_id = panel_id.clone();
cx.defer_in(window, move |this, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
});
});
Some(self.command_panels.borrow_mut().render(
&entry.id,
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
243 changes: 184 additions & 59 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Write as _, sync::Arc};

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
AnyElement, App, ContentMask, Hsla, IntoElement as _, ParentElement as _, Rgba, Styled as _,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use gpui_base::ElementExt as _;
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;
use crate::theme::{ActiveTheme as _, HighlightTheme};

const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;
Expand DownExpand Up@@ -61,10 +60,26 @@ impl CommandPanelCache {
}
}

#[derive(Clone)]
struct CommandTheme {
foreground: Hsla,
background: Hsla,
highlight_theme: Arc<HighlightTheme>,
}

impl CommandTheme {
fn matches(&self, other: &Self) -> bool {
self.foreground == other.foreground
&& self.background == other.background
&& Arc::ptr_eq(&self.highlight_theme, &other.highlight_theme)
}
}

struct CachedPanel {
command: String,
displayed_command: String,
command_snapshot: TermSnapshot,
command_rows: usize,
command_theme: Option<CommandTheme>,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
Expand All@@ -80,13 +95,14 @@ impl CachedPanel {
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let (command_snapshot, command_rows) = command_snapshot(command, cols, None);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
displayed_command,
command_snapshot,
command_rows,
command_theme: None,
cols,
output_emulator,
output: Vec::new(),
Expand All@@ -102,7 +118,8 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(command, self.cols, self.command_theme.as_ref());
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -127,7 +144,8 @@ impl CachedPanel {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, cols, self.command_theme.as_ref());
let output = self.output.clone();
self.rebuild_output(&output);
true
Expand DownExpand Up@@ -164,30 +182,37 @@ impl CachedPanel {
);
}

fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
fn update_command_theme(&mut self, command_theme: CommandTheme) {
if self
.command_theme
.as_ref()
.is_some_and(|cached| cached.matches(&command_theme))
{
return;
}
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, self.cols, Some(&command_theme));
self.command_theme = Some(command_theme);
}

fn render(&mut self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let command_theme = CommandTheme {
foreground: cx.theme().foreground,
background: cx.theme().background,
highlight_theme: cx.theme().highlight_theme.clone(),
};
self.update_command_theme(command_theme);
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
let command = grid_element(
&self.command_snapshot,
self.command_rows,
self.cols,
palette,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
Expand DownExpand Up@@ -242,41 +267,93 @@ fn grid_element(
.into_any_element()
}

fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
fn command_snapshot(
command: &str,
cols: usize,
command_theme: Option<&CommandTheme>,
) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(cols, MAX_COMMAND_ROWS);
let command = clamp_command(command, cols);
if let Some(command_theme) = command_theme {
emulator.feed(highlighted_command(&command, command_theme).as_bytes());
} else {
emulator.feed(command.as_bytes());
}
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn highlighted_command(command: &str, theme: &CommandTheme) -> String {
let highlights = highlight::highlight_source(command, "bash", &theme.highlight_theme);
let mut highlighted = String::new();
let mut cursor = 0;
for (range, style) in highlights {
if range.start > cursor {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..range.start]);
}
push_command_color(
&mut highlighted,
style.color.unwrap_or(theme.foreground),
theme.background,
);
highlighted.push_str(&command[range.clone()]);
cursor = range.end;
}
if cursor < command.len() {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..]);
}
highlighted
}

fn push_command_color(command: &mut String, foreground: Hsla, background: Hsla) {
let (r, g, b) = faded_command_rgb(foreground, background);
let _ = write!(command, "\x1b[38;2;{r};{g};{b}m");
}

fn faded_command_rgb(foreground: Hsla, background: Hsla) -> (u8, u8, u8) {
let faded = Rgba::from(background).blend(Rgba::from(foreground).opacity(0.7));
(
(faded.r * 255.) as u8,
(faded.g * 255.) as u8,
(faded.b * 255.) as u8,
)
}

fn clamp_command(command: &str, cols: usize) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
break;
}
lines.push(String::new());
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
if col == cols {
row += 1;
col = 0;
}
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == cols && chars.peek().is_some() {
result.push('…');
break;
}
last.push('…');
result.push(ch);
col += 1;
}
let rows = lines.len();
(lines.join("\n"), rows)
result
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -313,6 +390,14 @@ mod tests {
}
}

fn dark_command_theme() -> CommandTheme {
CommandTheme {
foreground: rgb(0xffffff).into(),
background: rgb(0x000000).into(),
highlight_theme: HighlightTheme::default_dark(),
}
}

#[test]
fn ansi_output_uses_terminal_green() {
let panel = CachedPanel::new("echo green", "\x1b[32mgreen\x1b[0m");
Expand All@@ -330,13 +415,53 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
let mut panel = CachedPanel::new(&"x".repeat(DEFAULT_COLS * MAX_COMMAND_ROWS + 1), "");
panel.update_command_theme(dark_command_theme());
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, DEFAULT_COLS - 1)
.is_some_and(|text| text == "…")
);
}

#[test]
fn command_highlight_is_faded_truecolor_in_terminal_cells() {
let command = "if true; then echo yes; fi";
let command_theme = dark_command_theme();
let clamped = clamp_command(command, DEFAULT_COLS);
let raw_keyword_color =
highlight::highlight_source(&clamped, "bash", &command_theme.highlight_theme)
.into_iter()
.find_map(|(range, style)| {
clamped[range]
.contains("if")
.then_some(style.color)
.flatten()
})
.expect("bash keyword highlight color");
let expected = faded_command_rgb(raw_keyword_color, command_theme.background);

let mut panel = CachedPanel::new(command, "");
panel.update_command_theme(command_theme);
let paint = layout_grid(
&panel.command_snapshot,
palette(),
false,
None,
false,
false,
);
let command = paint
.text_runs
.iter()
.find(|run| run.text.contains("if"))
.expect("highlighted command run");
let AnsiColor::Spec(color) = command.style.fg else {
panic!("command keyword should use truecolor foreground");
};
assert_eq!((color.r, color.g, color.b), expected);
}

#[test]
Expand Down
16 changes: 11 additions & 5 deletions crates/ui/src/chat/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1070,11 +1070,17 @@ impl ChatView {
command, output, ..
}) => {
let panel_id = entry.id.clone();
let on_cols_change = cx.listener(move |this, cols: &usize, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, *cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
let on_cols_change = cx.listener(move |_this, cols: &usize, window, cx| {
// Fires from `on_prepaint`, i.e. while `List` holds its state
// borrowed; remeasuring inline would panic. Defer past the frame.
let cols = *cols;
let panel_id = panel_id.clone();
cx.defer_in(window, move |this, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
});
});
Some(self.command_panels.borrow_mut().render(
&entry.id,
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
243 changes: 184 additions & 59 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Write as _, sync::Arc};

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
AnyElement, App, ContentMask, Hsla, IntoElement as _, ParentElement as _, Rgba, Styled as _,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use gpui_base::ElementExt as _;
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;
use crate::theme::{ActiveTheme as _, HighlightTheme};

const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;
Expand DownExpand Up@@ -61,10 +60,26 @@ impl CommandPanelCache {
}
}

#[derive(Clone)]
struct CommandTheme {
foreground: Hsla,
background: Hsla,
highlight_theme: Arc<HighlightTheme>,
}

impl CommandTheme {
fn matches(&self, other: &Self) -> bool {
self.foreground == other.foreground
&& self.background == other.background
&& Arc::ptr_eq(&self.highlight_theme, &other.highlight_theme)
}
}

struct CachedPanel {
command: String,
displayed_command: String,
command_snapshot: TermSnapshot,
command_rows: usize,
command_theme: Option<CommandTheme>,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
Expand All@@ -80,13 +95,14 @@ impl CachedPanel {
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let (command_snapshot, command_rows) = command_snapshot(command, cols, None);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
displayed_command,
command_snapshot,
command_rows,
command_theme: None,
cols,
output_emulator,
output: Vec::new(),
Expand All@@ -102,7 +118,8 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(command, self.cols, self.command_theme.as_ref());
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -127,7 +144,8 @@ impl CachedPanel {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, cols, self.command_theme.as_ref());
let output = self.output.clone();
self.rebuild_output(&output);
true
Expand DownExpand Up@@ -164,30 +182,37 @@ impl CachedPanel {
);
}

fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
fn update_command_theme(&mut self, command_theme: CommandTheme) {
if self
.command_theme
.as_ref()
.is_some_and(|cached| cached.matches(&command_theme))
{
return;
}
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, self.cols, Some(&command_theme));
self.command_theme = Some(command_theme);
}

fn render(&mut self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let command_theme = CommandTheme {
foreground: cx.theme().foreground,
background: cx.theme().background,
highlight_theme: cx.theme().highlight_theme.clone(),
};
self.update_command_theme(command_theme);
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
let command = grid_element(
&self.command_snapshot,
self.command_rows,
self.cols,
palette,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
Expand DownExpand Up@@ -242,41 +267,93 @@ fn grid_element(
.into_any_element()
}

fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
fn command_snapshot(
command: &str,
cols: usize,
command_theme: Option<&CommandTheme>,
) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(cols, MAX_COMMAND_ROWS);
let command = clamp_command(command, cols);
if let Some(command_theme) = command_theme {
emulator.feed(highlighted_command(&command, command_theme).as_bytes());
} else {
emulator.feed(command.as_bytes());
}
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn highlighted_command(command: &str, theme: &CommandTheme) -> String {
let highlights = highlight::highlight_source(command, "bash", &theme.highlight_theme);
let mut highlighted = String::new();
let mut cursor = 0;
for (range, style) in highlights {
if range.start > cursor {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..range.start]);
}
push_command_color(
&mut highlighted,
style.color.unwrap_or(theme.foreground),
theme.background,
);
highlighted.push_str(&command[range.clone()]);
cursor = range.end;
}
if cursor < command.len() {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..]);
}
highlighted
}

fn push_command_color(command: &mut String, foreground: Hsla, background: Hsla) {
let (r, g, b) = faded_command_rgb(foreground, background);
let _ = write!(command, "\x1b[38;2;{r};{g};{b}m");
}

fn faded_command_rgb(foreground: Hsla, background: Hsla) -> (u8, u8, u8) {
let faded = Rgba::from(background).blend(Rgba::from(foreground).opacity(0.7));
(
(faded.r * 255.) as u8,
(faded.g * 255.) as u8,
(faded.b * 255.) as u8,
)
}

fn clamp_command(command: &str, cols: usize) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
break;
}
lines.push(String::new());
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
if col == cols {
row += 1;
col = 0;
}
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == cols && chars.peek().is_some() {
result.push('…');
break;
}
last.push('…');
result.push(ch);
col += 1;
}
let rows = lines.len();
(lines.join("\n"), rows)
result
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -313,6 +390,14 @@ mod tests {
}
}

fn dark_command_theme() -> CommandTheme {
CommandTheme {
foreground: rgb(0xffffff).into(),
background: rgb(0x000000).into(),
highlight_theme: HighlightTheme::default_dark(),
}
}

#[test]
fn ansi_output_uses_terminal_green() {
let panel = CachedPanel::new("echo green", "\x1b[32mgreen\x1b[0m");
Expand All@@ -330,13 +415,53 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
let mut panel = CachedPanel::new(&"x".repeat(DEFAULT_COLS * MAX_COMMAND_ROWS + 1), "");
panel.update_command_theme(dark_command_theme());
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, DEFAULT_COLS - 1)
.is_some_and(|text| text == "…")
);
}

#[test]
fn command_highlight_is_faded_truecolor_in_terminal_cells() {
let command = "if true; then echo yes; fi";
let command_theme = dark_command_theme();
let clamped = clamp_command(command, DEFAULT_COLS);
let raw_keyword_color =
highlight::highlight_source(&clamped, "bash", &command_theme.highlight_theme)
.into_iter()
.find_map(|(range, style)| {
clamped[range]
.contains("if")
.then_some(style.color)
.flatten()
})
.expect("bash keyword highlight color");
let expected = faded_command_rgb(raw_keyword_color, command_theme.background);

let mut panel = CachedPanel::new(command, "");
panel.update_command_theme(command_theme);
let paint = layout_grid(
&panel.command_snapshot,
palette(),
false,
None,
false,
false,
);
let command = paint
.text_runs
.iter()
.find(|run| run.text.contains("if"))
.expect("highlighted command run");
let AnsiColor::Spec(color) = command.style.fg else {
panic!("command keyword should use truecolor foreground");
};
assert_eq!((color.r, color.g, color.b), expected);
}

#[test]
Expand Down
16 changes: 11 additions & 5 deletions crates/ui/src/chat/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1070,11 +1070,17 @@ impl ChatView {
command, output, ..
}) => {
let panel_id = entry.id.clone();
let on_cols_change = cx.listener(move |this, cols: &usize, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, *cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
let on_cols_change = cx.listener(move |_this, cols: &usize, window, cx| {
// Fires from `on_prepaint`, i.e. while `List` holds its state
// borrowed; remeasuring inline would panic. Defer past the frame.
let cols = *cols;
let panel_id = panel_id.clone();
cx.defer_in(window, move |this, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
});
});
Some(self.command_panels.borrow_mut().render(
&entry.id,
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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
243 changes: 184 additions & 59 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Write as _, sync::Arc};

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
AnyElement, App, ContentMask, Hsla, IntoElement as _, ParentElement as _, Rgba, Styled as _,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use gpui_base::ElementExt as _;
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;
use crate::theme::{ActiveTheme as _, HighlightTheme};

const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;
Expand DownExpand Up@@ -61,10 +60,26 @@ impl CommandPanelCache {
}
}

#[derive(Clone)]
struct CommandTheme {
foreground: Hsla,
background: Hsla,
highlight_theme: Arc<HighlightTheme>,
}

impl CommandTheme {
fn matches(&self, other: &Self) -> bool {
self.foreground == other.foreground
&& self.background == other.background
&& Arc::ptr_eq(&self.highlight_theme, &other.highlight_theme)
}
}

struct CachedPanel {
command: String,
displayed_command: String,
command_snapshot: TermSnapshot,
command_rows: usize,
command_theme: Option<CommandTheme>,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
Expand All@@ -80,13 +95,14 @@ impl CachedPanel {
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let (command_snapshot, command_rows) = command_snapshot(command, cols, None);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
displayed_command,
command_snapshot,
command_rows,
command_theme: None,
cols,
output_emulator,
output: Vec::new(),
Expand All@@ -102,7 +118,8 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(command, self.cols, self.command_theme.as_ref());
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -127,7 +144,8 @@ impl CachedPanel {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, cols, self.command_theme.as_ref());
let output = self.output.clone();
self.rebuild_output(&output);
true
Expand DownExpand Up@@ -164,30 +182,37 @@ impl CachedPanel {
);
}

fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
fn update_command_theme(&mut self, command_theme: CommandTheme) {
if self
.command_theme
.as_ref()
.is_some_and(|cached| cached.matches(&command_theme))
{
return;
}
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, self.cols, Some(&command_theme));
self.command_theme = Some(command_theme);
}

fn render(&mut self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let command_theme = CommandTheme {
foreground: cx.theme().foreground,
background: cx.theme().background,
highlight_theme: cx.theme().highlight_theme.clone(),
};
self.update_command_theme(command_theme);
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
let command = grid_element(
&self.command_snapshot,
self.command_rows,
self.cols,
palette,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
Expand DownExpand Up@@ -242,41 +267,93 @@ fn grid_element(
.into_any_element()
}

fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
fn command_snapshot(
command: &str,
cols: usize,
command_theme: Option<&CommandTheme>,
) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(cols, MAX_COMMAND_ROWS);
let command = clamp_command(command, cols);
if let Some(command_theme) = command_theme {
emulator.feed(highlighted_command(&command, command_theme).as_bytes());
} else {
emulator.feed(command.as_bytes());
}
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn highlighted_command(command: &str, theme: &CommandTheme) -> String {
let highlights = highlight::highlight_source(command, "bash", &theme.highlight_theme);
let mut highlighted = String::new();
let mut cursor = 0;
for (range, style) in highlights {
if range.start > cursor {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..range.start]);
}
push_command_color(
&mut highlighted,
style.color.unwrap_or(theme.foreground),
theme.background,
);
highlighted.push_str(&command[range.clone()]);
cursor = range.end;
}
if cursor < command.len() {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..]);
}
highlighted
}

fn push_command_color(command: &mut String, foreground: Hsla, background: Hsla) {
let (r, g, b) = faded_command_rgb(foreground, background);
let _ = write!(command, "\x1b[38;2;{r};{g};{b}m");
}

fn faded_command_rgb(foreground: Hsla, background: Hsla) -> (u8, u8, u8) {
let faded = Rgba::from(background).blend(Rgba::from(foreground).opacity(0.7));
(
(faded.r * 255.) as u8,
(faded.g * 255.) as u8,
(faded.b * 255.) as u8,
)
}

fn clamp_command(command: &str, cols: usize) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
break;
}
lines.push(String::new());
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
if col == cols {
row += 1;
col = 0;
}
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == cols && chars.peek().is_some() {
result.push('…');
break;
}
last.push('…');
result.push(ch);
col += 1;
}
let rows = lines.len();
(lines.join("\n"), rows)
result
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -313,6 +390,14 @@ mod tests {
}
}

fn dark_command_theme() -> CommandTheme {
CommandTheme {
foreground: rgb(0xffffff).into(),
background: rgb(0x000000).into(),
highlight_theme: HighlightTheme::default_dark(),
}
}

#[test]
fn ansi_output_uses_terminal_green() {
let panel = CachedPanel::new("echo green", "\x1b[32mgreen\x1b[0m");
Expand All@@ -330,13 +415,53 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
let mut panel = CachedPanel::new(&"x".repeat(DEFAULT_COLS * MAX_COMMAND_ROWS + 1), "");
panel.update_command_theme(dark_command_theme());
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, DEFAULT_COLS - 1)
.is_some_and(|text| text == "…")
);
}

#[test]
fn command_highlight_is_faded_truecolor_in_terminal_cells() {
let command = "if true; then echo yes; fi";
let command_theme = dark_command_theme();
let clamped = clamp_command(command, DEFAULT_COLS);
let raw_keyword_color =
highlight::highlight_source(&clamped, "bash", &command_theme.highlight_theme)
.into_iter()
.find_map(|(range, style)| {
clamped[range]
.contains("if")
.then_some(style.color)
.flatten()
})
.expect("bash keyword highlight color");
let expected = faded_command_rgb(raw_keyword_color, command_theme.background);

let mut panel = CachedPanel::new(command, "");
panel.update_command_theme(command_theme);
let paint = layout_grid(
&panel.command_snapshot,
palette(),
false,
None,
false,
false,
);
let command = paint
.text_runs
.iter()
.find(|run| run.text.contains("if"))
.expect("highlighted command run");
let AnsiColor::Spec(color) = command.style.fg else {
panic!("command keyword should use truecolor foreground");
};
assert_eq!((color.r, color.g, color.b), expected);
}

#[test]
Expand Down
16 changes: 11 additions & 5 deletions crates/ui/src/chat/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1070,11 +1070,17 @@ impl ChatView {
command, output, ..
}) => {
let panel_id = entry.id.clone();
let on_cols_change = cx.listener(move |this, cols: &usize, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, *cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
let on_cols_change = cx.listener(move |_this, cols: &usize, window, cx| {
// Fires from `on_prepaint`, i.e. while `List` holds its state
// borrowed; remeasuring inline would panic. Defer past the frame.
let cols = *cols;
let panel_id = panel_id.clone();
cx.defer_in(window, move |this, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
});
});
Some(self.command_panels.borrow_mut().render(
&entry.id,
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
243 changes: 184 additions & 59 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Write as _, sync::Arc};

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
AnyElement, App, ContentMask, Hsla, IntoElement as _, ParentElement as _, Rgba, Styled as _,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use gpui_base::ElementExt as _;
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;
use crate::theme::{ActiveTheme as _, HighlightTheme};

const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;
Expand DownExpand Up@@ -61,10 +60,26 @@ impl CommandPanelCache {
}
}

#[derive(Clone)]
struct CommandTheme {
foreground: Hsla,
background: Hsla,
highlight_theme: Arc<HighlightTheme>,
}

impl CommandTheme {
fn matches(&self, other: &Self) -> bool {
self.foreground == other.foreground
&& self.background == other.background
&& Arc::ptr_eq(&self.highlight_theme, &other.highlight_theme)
}
}

struct CachedPanel {
command: String,
displayed_command: String,
command_snapshot: TermSnapshot,
command_rows: usize,
command_theme: Option<CommandTheme>,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
Expand All@@ -80,13 +95,14 @@ impl CachedPanel {
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let (command_snapshot, command_rows) = command_snapshot(command, cols, None);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
displayed_command,
command_snapshot,
command_rows,
command_theme: None,
cols,
output_emulator,
output: Vec::new(),
Expand All@@ -102,7 +118,8 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(command, self.cols, self.command_theme.as_ref());
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -127,7 +144,8 @@ impl CachedPanel {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, cols, self.command_theme.as_ref());
let output = self.output.clone();
self.rebuild_output(&output);
true
Expand DownExpand Up@@ -164,30 +182,37 @@ impl CachedPanel {
);
}

fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
fn update_command_theme(&mut self, command_theme: CommandTheme) {
if self
.command_theme
.as_ref()
.is_some_and(|cached| cached.matches(&command_theme))
{
return;
}
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, self.cols, Some(&command_theme));
self.command_theme = Some(command_theme);
}

fn render(&mut self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let command_theme = CommandTheme {
foreground: cx.theme().foreground,
background: cx.theme().background,
highlight_theme: cx.theme().highlight_theme.clone(),
};
self.update_command_theme(command_theme);
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
let command = grid_element(
&self.command_snapshot,
self.command_rows,
self.cols,
palette,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
Expand DownExpand Up@@ -242,41 +267,93 @@ fn grid_element(
.into_any_element()
}

fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
fn command_snapshot(
command: &str,
cols: usize,
command_theme: Option<&CommandTheme>,
) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(cols, MAX_COMMAND_ROWS);
let command = clamp_command(command, cols);
if let Some(command_theme) = command_theme {
emulator.feed(highlighted_command(&command, command_theme).as_bytes());
} else {
emulator.feed(command.as_bytes());
}
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn highlighted_command(command: &str, theme: &CommandTheme) -> String {
let highlights = highlight::highlight_source(command, "bash", &theme.highlight_theme);
let mut highlighted = String::new();
let mut cursor = 0;
for (range, style) in highlights {
if range.start > cursor {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..range.start]);
}
push_command_color(
&mut highlighted,
style.color.unwrap_or(theme.foreground),
theme.background,
);
highlighted.push_str(&command[range.clone()]);
cursor = range.end;
}
if cursor < command.len() {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..]);
}
highlighted
}

fn push_command_color(command: &mut String, foreground: Hsla, background: Hsla) {
let (r, g, b) = faded_command_rgb(foreground, background);
let _ = write!(command, "\x1b[38;2;{r};{g};{b}m");
}

fn faded_command_rgb(foreground: Hsla, background: Hsla) -> (u8, u8, u8) {
let faded = Rgba::from(background).blend(Rgba::from(foreground).opacity(0.7));
(
(faded.r * 255.) as u8,
(faded.g * 255.) as u8,
(faded.b * 255.) as u8,
)
}

fn clamp_command(command: &str, cols: usize) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
break;
}
lines.push(String::new());
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
if col == cols {
row += 1;
col = 0;
}
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == cols && chars.peek().is_some() {
result.push('…');
break;
}
last.push('…');
result.push(ch);
col += 1;
}
let rows = lines.len();
(lines.join("\n"), rows)
result
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -313,6 +390,14 @@ mod tests {
}
}

fn dark_command_theme() -> CommandTheme {
CommandTheme {
foreground: rgb(0xffffff).into(),
background: rgb(0x000000).into(),
highlight_theme: HighlightTheme::default_dark(),
}
}

#[test]
fn ansi_output_uses_terminal_green() {
let panel = CachedPanel::new("echo green", "\x1b[32mgreen\x1b[0m");
Expand All@@ -330,13 +415,53 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
let mut panel = CachedPanel::new(&"x".repeat(DEFAULT_COLS * MAX_COMMAND_ROWS + 1), "");
panel.update_command_theme(dark_command_theme());
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, DEFAULT_COLS - 1)
.is_some_and(|text| text == "…")
);
}

#[test]
fn command_highlight_is_faded_truecolor_in_terminal_cells() {
let command = "if true; then echo yes; fi";
let command_theme = dark_command_theme();
let clamped = clamp_command(command, DEFAULT_COLS);
let raw_keyword_color =
highlight::highlight_source(&clamped, "bash", &command_theme.highlight_theme)
.into_iter()
.find_map(|(range, style)| {
clamped[range]
.contains("if")
.then_some(style.color)
.flatten()
})
.expect("bash keyword highlight color");
let expected = faded_command_rgb(raw_keyword_color, command_theme.background);

let mut panel = CachedPanel::new(command, "");
panel.update_command_theme(command_theme);
let paint = layout_grid(
&panel.command_snapshot,
palette(),
false,
None,
false,
false,
);
let command = paint
.text_runs
.iter()
.find(|run| run.text.contains("if"))
.expect("highlighted command run");
let AnsiColor::Spec(color) = command.style.fg else {
panic!("command keyword should use truecolor foreground");
};
assert_eq!((color.r, color.g, color.b), expected);
}

#[test]
Expand Down
16 changes: 11 additions & 5 deletions crates/ui/src/chat/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1070,11 +1070,17 @@ impl ChatView {
command, output, ..
}) => {
let panel_id = entry.id.clone();
let on_cols_change = cx.listener(move |this, cols: &usize, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, *cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
let on_cols_change = cx.listener(move |_this, cols: &usize, window, cx| {
// Fires from `on_prepaint`, i.e. while `List` holds its state
// borrowed; remeasuring inline would panic. Defer past the frame.
let cols = *cols;
let panel_id = panel_id.clone();
cx.defer_in(window, move |this, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
});
});
Some(self.command_panels.borrow_mut().render(
&entry.id,
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
243 changes: 184 additions & 59 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Write as _, sync::Arc};

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
AnyElement, App, ContentMask, Hsla, IntoElement as _, ParentElement as _, Rgba, Styled as _,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use gpui_base::ElementExt as _;
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;
use crate::theme::{ActiveTheme as _, HighlightTheme};

const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;
Expand DownExpand Up@@ -61,10 +60,26 @@ impl CommandPanelCache {
}
}

#[derive(Clone)]
struct CommandTheme {
foreground: Hsla,
background: Hsla,
highlight_theme: Arc<HighlightTheme>,
}

impl CommandTheme {
fn matches(&self, other: &Self) -> bool {
self.foreground == other.foreground
&& self.background == other.background
&& Arc::ptr_eq(&self.highlight_theme, &other.highlight_theme)
}
}

struct CachedPanel {
command: String,
displayed_command: String,
command_snapshot: TermSnapshot,
command_rows: usize,
command_theme: Option<CommandTheme>,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
Expand All@@ -80,13 +95,14 @@ impl CachedPanel {
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let (command_snapshot, command_rows) = command_snapshot(command, cols, None);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
displayed_command,
command_snapshot,
command_rows,
command_theme: None,
cols,
output_emulator,
output: Vec::new(),
Expand All@@ -102,7 +118,8 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(command, self.cols, self.command_theme.as_ref());
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -127,7 +144,8 @@ impl CachedPanel {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, cols, self.command_theme.as_ref());
let output = self.output.clone();
self.rebuild_output(&output);
true
Expand DownExpand Up@@ -164,30 +182,37 @@ impl CachedPanel {
);
}

fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
fn update_command_theme(&mut self, command_theme: CommandTheme) {
if self
.command_theme
.as_ref()
.is_some_and(|cached| cached.matches(&command_theme))
{
return;
}
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, self.cols, Some(&command_theme));
self.command_theme = Some(command_theme);
}

fn render(&mut self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let command_theme = CommandTheme {
foreground: cx.theme().foreground,
background: cx.theme().background,
highlight_theme: cx.theme().highlight_theme.clone(),
};
self.update_command_theme(command_theme);
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
let command = grid_element(
&self.command_snapshot,
self.command_rows,
self.cols,
palette,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
Expand DownExpand Up@@ -242,41 +267,93 @@ fn grid_element(
.into_any_element()
}

fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
fn command_snapshot(
command: &str,
cols: usize,
command_theme: Option<&CommandTheme>,
) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(cols, MAX_COMMAND_ROWS);
let command = clamp_command(command, cols);
if let Some(command_theme) = command_theme {
emulator.feed(highlighted_command(&command, command_theme).as_bytes());
} else {
emulator.feed(command.as_bytes());
}
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn highlighted_command(command: &str, theme: &CommandTheme) -> String {
let highlights = highlight::highlight_source(command, "bash", &theme.highlight_theme);
let mut highlighted = String::new();
let mut cursor = 0;
for (range, style) in highlights {
if range.start > cursor {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..range.start]);
}
push_command_color(
&mut highlighted,
style.color.unwrap_or(theme.foreground),
theme.background,
);
highlighted.push_str(&command[range.clone()]);
cursor = range.end;
}
if cursor < command.len() {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..]);
}
highlighted
}

fn push_command_color(command: &mut String, foreground: Hsla, background: Hsla) {
let (r, g, b) = faded_command_rgb(foreground, background);
let _ = write!(command, "\x1b[38;2;{r};{g};{b}m");
}

fn faded_command_rgb(foreground: Hsla, background: Hsla) -> (u8, u8, u8) {
let faded = Rgba::from(background).blend(Rgba::from(foreground).opacity(0.7));
(
(faded.r * 255.) as u8,
(faded.g * 255.) as u8,
(faded.b * 255.) as u8,
)
}

fn clamp_command(command: &str, cols: usize) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
break;
}
lines.push(String::new());
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
if col == cols {
row += 1;
col = 0;
}
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == cols && chars.peek().is_some() {
result.push('…');
break;
}
last.push('…');
result.push(ch);
col += 1;
}
let rows = lines.len();
(lines.join("\n"), rows)
result
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -313,6 +390,14 @@ mod tests {
}
}

fn dark_command_theme() -> CommandTheme {
CommandTheme {
foreground: rgb(0xffffff).into(),
background: rgb(0x000000).into(),
highlight_theme: HighlightTheme::default_dark(),
}
}

#[test]
fn ansi_output_uses_terminal_green() {
let panel = CachedPanel::new("echo green", "\x1b[32mgreen\x1b[0m");
Expand All@@ -330,13 +415,53 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
let mut panel = CachedPanel::new(&"x".repeat(DEFAULT_COLS * MAX_COMMAND_ROWS + 1), "");
panel.update_command_theme(dark_command_theme());
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, DEFAULT_COLS - 1)
.is_some_and(|text| text == "…")
);
}

#[test]
fn command_highlight_is_faded_truecolor_in_terminal_cells() {
let command = "if true; then echo yes; fi";
let command_theme = dark_command_theme();
let clamped = clamp_command(command, DEFAULT_COLS);
let raw_keyword_color =
highlight::highlight_source(&clamped, "bash", &command_theme.highlight_theme)
.into_iter()
.find_map(|(range, style)| {
clamped[range]
.contains("if")
.then_some(style.color)
.flatten()
})
.expect("bash keyword highlight color");
let expected = faded_command_rgb(raw_keyword_color, command_theme.background);

let mut panel = CachedPanel::new(command, "");
panel.update_command_theme(command_theme);
let paint = layout_grid(
&panel.command_snapshot,
palette(),
false,
None,
false,
false,
);
let command = paint
.text_runs
.iter()
.find(|run| run.text.contains("if"))
.expect("highlighted command run");
let AnsiColor::Spec(color) = command.style.fg else {
panic!("command keyword should use truecolor foreground");
};
assert_eq!((color.r, color.g, color.b), expected);
}

#[test]
Expand Down
16 changes: 11 additions & 5 deletions crates/ui/src/chat/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1070,11 +1070,17 @@ impl ChatView {
command, output, ..
}) => {
let panel_id = entry.id.clone();
let on_cols_change = cx.listener(move |this, cols: &usize, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, *cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
let on_cols_change = cx.listener(move |_this, cols: &usize, window, cx| {
// Fires from `on_prepaint`, i.e. while `List` holds its state
// borrowed; remeasuring inline would panic. Defer past the frame.
let cols = *cols;
let panel_id = panel_id.clone();
cx.defer_in(window, move |this, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
});
});
Some(self.command_panels.borrow_mut().render(
&entry.id,
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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
243 changes: 184 additions & 59 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Write as _, sync::Arc};

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
AnyElement, App, ContentMask, Hsla, IntoElement as _, ParentElement as _, Rgba, Styled as _,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use gpui_base::ElementExt as _;
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;
use crate::theme::{ActiveTheme as _, HighlightTheme};

const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;
Expand DownExpand Up@@ -61,10 +60,26 @@ impl CommandPanelCache {
}
}

#[derive(Clone)]
struct CommandTheme {
foreground: Hsla,
background: Hsla,
highlight_theme: Arc<HighlightTheme>,
}

impl CommandTheme {
fn matches(&self, other: &Self) -> bool {
self.foreground == other.foreground
&& self.background == other.background
&& Arc::ptr_eq(&self.highlight_theme, &other.highlight_theme)
}
}

struct CachedPanel {
command: String,
displayed_command: String,
command_snapshot: TermSnapshot,
command_rows: usize,
command_theme: Option<CommandTheme>,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
Expand All@@ -80,13 +95,14 @@ impl CachedPanel {
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let (command_snapshot, command_rows) = command_snapshot(command, cols, None);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
displayed_command,
command_snapshot,
command_rows,
command_theme: None,
cols,
output_emulator,
output: Vec::new(),
Expand All@@ -102,7 +118,8 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(command, self.cols, self.command_theme.as_ref());
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -127,7 +144,8 @@ impl CachedPanel {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, cols, self.command_theme.as_ref());
let output = self.output.clone();
self.rebuild_output(&output);
true
Expand DownExpand Up@@ -164,30 +182,37 @@ impl CachedPanel {
);
}

fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
fn update_command_theme(&mut self, command_theme: CommandTheme) {
if self
.command_theme
.as_ref()
.is_some_and(|cached| cached.matches(&command_theme))
{
return;
}
(self.command_snapshot, self.command_rows) =
command_snapshot(&self.command, self.cols, Some(&command_theme));
self.command_theme = Some(command_theme);
}

fn render(&mut self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let command_theme = CommandTheme {
foreground: cx.theme().foreground,
background: cx.theme().background,
highlight_theme: cx.theme().highlight_theme.clone(),
};
self.update_command_theme(command_theme);
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
let command = grid_element(
&self.command_snapshot,
self.command_rows,
self.cols,
palette,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
Expand DownExpand Up@@ -242,41 +267,93 @@ fn grid_element(
.into_any_element()
}

fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
fn command_snapshot(
command: &str,
cols: usize,
command_theme: Option<&CommandTheme>,
) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(cols, MAX_COMMAND_ROWS);
let command = clamp_command(command, cols);
if let Some(command_theme) = command_theme {
emulator.feed(highlighted_command(&command, command_theme).as_bytes());
} else {
emulator.feed(command.as_bytes());
}
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn highlighted_command(command: &str, theme: &CommandTheme) -> String {
let highlights = highlight::highlight_source(command, "bash", &theme.highlight_theme);
let mut highlighted = String::new();
let mut cursor = 0;
for (range, style) in highlights {
if range.start > cursor {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..range.start]);
}
push_command_color(
&mut highlighted,
style.color.unwrap_or(theme.foreground),
theme.background,
);
highlighted.push_str(&command[range.clone()]);
cursor = range.end;
}
if cursor < command.len() {
push_command_color(&mut highlighted, theme.foreground, theme.background);
highlighted.push_str(&command[cursor..]);
}
highlighted
}

fn push_command_color(command: &mut String, foreground: Hsla, background: Hsla) {
let (r, g, b) = faded_command_rgb(foreground, background);
let _ = write!(command, "\x1b[38;2;{r};{g};{b}m");
}

fn faded_command_rgb(foreground: Hsla, background: Hsla) -> (u8, u8, u8) {
let faded = Rgba::from(background).blend(Rgba::from(foreground).opacity(0.7));
(
(faded.r * 255.) as u8,
(faded.g * 255.) as u8,
(faded.b * 255.) as u8,
)
}

fn clamp_command(command: &str, cols: usize) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
break;
}
lines.push(String::new());
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
if col == cols {
row += 1;
col = 0;
}
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == cols && chars.peek().is_some() {
result.push('…');
break;
}
last.push('…');
result.push(ch);
col += 1;
}
let rows = lines.len();
(lines.join("\n"), rows)
result
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -313,6 +390,14 @@ mod tests {
}
}

fn dark_command_theme() -> CommandTheme {
CommandTheme {
foreground: rgb(0xffffff).into(),
background: rgb(0x000000).into(),
highlight_theme: HighlightTheme::default_dark(),
}
}

#[test]
fn ansi_output_uses_terminal_green() {
let panel = CachedPanel::new("echo green", "\x1b[32mgreen\x1b[0m");
Expand All@@ -330,13 +415,53 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
let mut panel = CachedPanel::new(&"x".repeat(DEFAULT_COLS * MAX_COMMAND_ROWS + 1), "");
panel.update_command_theme(dark_command_theme());
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, DEFAULT_COLS - 1)
.is_some_and(|text| text == "…")
);
}

#[test]
fn command_highlight_is_faded_truecolor_in_terminal_cells() {
let command = "if true; then echo yes; fi";
let command_theme = dark_command_theme();
let clamped = clamp_command(command, DEFAULT_COLS);
let raw_keyword_color =
highlight::highlight_source(&clamped, "bash", &command_theme.highlight_theme)
.into_iter()
.find_map(|(range, style)| {
clamped[range]
.contains("if")
.then_some(style.color)
.flatten()
})
.expect("bash keyword highlight color");
let expected = faded_command_rgb(raw_keyword_color, command_theme.background);

let mut panel = CachedPanel::new(command, "");
panel.update_command_theme(command_theme);
let paint = layout_grid(
&panel.command_snapshot,
palette(),
false,
None,
false,
false,
);
let command = paint
.text_runs
.iter()
.find(|run| run.text.contains("if"))
.expect("highlighted command run");
let AnsiColor::Spec(color) = command.style.fg else {
panic!("command keyword should use truecolor foreground");
};
assert_eq!((color.r, color.g, color.b), expected);
}

#[test]
Expand Down
16 changes: 11 additions & 5 deletions crates/ui/src/chat/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1070,11 +1070,17 @@ impl ChatView {
command, output, ..
}) => {
let panel_id = entry.id.clone();
let on_cols_change = cx.listener(move |this, cols: &usize, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, *cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
let on_cols_change = cx.listener(move |_this, cols: &usize, window, cx| {
// Fires from `on_prepaint`, i.e. while `List` holds its state
// borrowed; remeasuring inline would panic. Defer past the frame.
let cols = *cols;
let panel_id = panel_id.clone();
cx.defer_in(window, move |this, _window, cx| {
if this.command_panels.borrow_mut().resize(&panel_id, cols) {
this.list_state.remeasure_items(turn..turn + 1);
cx.notify();
}
});
});
Some(self.command_panels.borrow_mut().render(
&entry.id,
Expand Down