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
38 changes: 26 additions & 12 deletions packages/rust/crates/opentui/src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,8 @@ pub(crate) struct AppInner {
/// Whether the app runs on a remote terminal, which waits here until [`App::run`].
remote: bool,
remote_terminal: RefCell<Option<RemoteTerminal>>,
width_method: Cell<WidthMethod>,
/// A detached app's parent Session, whose terminal state it copies before it measures text.
parent: std::cell::OnceCell<Session>,
root: RefCell<Option<View>>,
registry: RefCell<HashMap<u32, Weak<dyn Behavior>>>,
next_num: Cell<u32>,
Expand Down Expand Up @@ -494,9 +495,11 @@ impl App {
}

/// An app on a detached Session that never runs, for painting widgets offscreen, with a manual clock.
pub(crate) fn detached(session: Session, options: AppOptions) -> Result<Self> {
pub(crate) fn detached(session: Session, parent: Session, options: AppOptions) -> Result<Self> {
let start = Instant::now();
Self::with_session(session, options, Clock::Manual { start, now: Cell::new(start) }, None)
let app = Self::with_session(session, options, Clock::Manual { start, now: Cell::new(start) }, None)?;
let _ = app.0.parent.set(parent);
Ok(app)
}

fn with_session(
Expand All @@ -506,7 +509,6 @@ impl App {
remote_terminal: Option<RemoteTerminal>,
) -> Result<Self> {
let renderer = session.renderer_state()?;
let width_method = session.capabilities()?.width_method;
let title = options.title.clone();
let remote = remote_terminal.is_some();
let app = Self(Rc::new(AppInner {
Expand All @@ -515,7 +517,7 @@ impl App {
options,
remote,
remote_terminal: RefCell::new(remote_terminal),
width_method: Cell::new(width_method),
parent: std::cell::OnceCell::new(),
root: RefCell::new(None),
registry: RefCell::new(HashMap::new()),
next_num: Cell::new(1),
Expand Down Expand Up @@ -626,6 +628,17 @@ impl App {
&self.0.session
}

/// The Session. A detached app first copies its parent's terminal state, so a text node made now measures as the
/// parent draws. Not while a frame runs, which native code rejects; `Scrollback` copies before each frame.
pub(crate) fn synced_session(&self) -> &Session {
if !self.0.in_frame.get()
&& let Some(parent) = self.0.parent.get()
{
let _ = self.0.session.sync_detached(parent);
}
&self.0.session
}

/// The terminal size in cells.
pub fn size(&self) -> (u16, u16) {
self.0.size.get()
Expand All @@ -635,7 +648,11 @@ impl App {
/// native owners of text, such as [`Buffer::new`](crate::native::Buffer::new), so their text lines up with the
/// app's.
pub fn width_method(&self) -> WidthMethod {
self.0.width_method.get()
// Native draws NoZwj as Unicode, as Core reads it.
match self.synced_session().capabilities().map(|capabilities| capabilities.width_method) {
Ok(WidthMethod::NoZwj) | Err(_) => WidthMethod::Unicode,
Ok(method) => method,
}
}

/// Frames painted so far.
Expand Down Expand Up @@ -668,7 +685,7 @@ impl App {

/// Whether the terminal shows OSC 8 hyperlinks, as far as it has reported.
pub(crate) fn hyperlinks(&self) -> bool {
let capabilities = self.0.session.capabilities();
let capabilities = self.synced_session().capabilities();
capabilities.is_ok_and(|capabilities| capabilities.flags.contains(crate::native::CapabilityFlags::HYPERLINKS))
}

Expand Down Expand Up @@ -1452,14 +1469,14 @@ impl App {
}
HostRequest::LayoutChanged { .. } | HostRequest::Scroll { .. } => {}
HostRequest::Record { slots, recorder } => {
let context = self.0.session.context().clone();
let (context, width_method) = (self.0.session.context().clone(), self.width_method());
for slot in slots {
if let Some(widget) = self.lookup(slot.num) {
if widget.element().has_filters() {
self.filtered_slot(&widget, slot);
}
let hooks = widget.element().own_hooks();
let mut painter = Painter::new(recorder, slot, hooks, &context, self.width_method());
let mut painter = Painter::new(recorder, slot, hooks, &context, width_method);
widget.paint(&mut painter);
painter.finish()?;
}
Expand Down Expand Up @@ -1520,9 +1537,6 @@ impl App {
self.0.terminal_active.set(true);
self.0.size.set(host.size());
self.0.proxy.set_waker(Some(host.waker()));
if let Some(capabilities) = self.report(self.0.session.capabilities()) {
self.0.width_method.set(capabilities.width_method);
}
let title = self.0.title.borrow().clone();
if let Some(title) = title {
self.report(self.0.session.control(Control::Title(&title)));
Expand Down
7 changes: 4 additions & 3 deletions packages/rust/crates/opentui/src/split/scrollback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl Scrollback {
session.attach_renderer(renderer.width.max(1), 1, Remote::Remote, &[])?;
session.sync_detached(parent)?;
let theme = Theme { background: Color::TRANSPARENT, ..theme };
let app = App::detached(session.clone(), AppOptions::default().with_theme(theme))?;
let app = App::detached(session.clone(), parent.clone(), AppOptions::default().with_theme(theme))?;
// The detached app never runs; messages logged meanwhile belong to the parent.
crate::console::unregister(app.console_id());
Ok(Self(Rc::new(Inner { app, session, parent: parent.clone() })))
Expand Down Expand Up @@ -137,6 +137,8 @@ impl Scrollback {
fn render(&self, holder: &View, width: u32, height: Option<u32>, rows: u32) -> Result<(Buffer, u32)> {
let inner = &self.0;
inner.session.sync_detached(&inner.parent)?;
// Read before painting: the draft keeps the Session busy until it is dropped.
let width_method = inner.app.width_method();
let mut rows = height.unwrap_or(rows).max(1);
let mut pass = 0;
let draft = loop {
Expand All @@ -150,7 +152,6 @@ impl Scrollback {
rows = measured;
pass += 1;
};
let width_method = inner.parent.capabilities()?.width_method;
let buffer = Buffer::new(inner.parent.context(), width, rows, width_method)?;
draft.copy_to(&buffer)?;
Ok((buffer, rows))
Expand Down Expand Up @@ -231,7 +232,7 @@ impl ScrollbackSurface {
return Ok(None);
}
let parent = &self.scrollback.0.parent;
let buffer = Buffer::new(parent.context(), *width, end - start, parent.capabilities()?.width_method)?;
let buffer = Buffer::new(parent.context(), *width, end - start, self.scrollback.0.app.width_method())?;
buffer.compose(source, 0, -(start as i32))?;
let start_on_new_line = self.next_start_on_new_line.replace(false);
Ok(Some(SplitSnapshot {
Expand Down
14 changes: 10 additions & 4 deletions packages/rust/crates/opentui/src/widget/line_numbers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use super::{AnyWidget, Behavior, Element, Painter, Widget, build, handle};
use crate::app::{App, Cx};
use crate::input::MouseEvent;
use crate::layout::{FlexDirection, LayoutProperty, Length};
use crate::native::{Hooks, NodeKind};
use crate::native::{Hooks, NodeKind, WidthMethod};
use crate::style::{Color, Style};
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
Expand Down Expand Up @@ -112,6 +112,7 @@ pub(crate) struct GutterInner {
pub target: RefCell<Weak<dyn Behavior>>,
pub state: RefCell<GutterState>,
width: Cell<u32>,
sign_method: Cell<Option<WidthMethod>>,
}

impl GutterInner {
Expand All @@ -121,14 +122,18 @@ impl GutterInner {
target: RefCell::new(Weak::<GutterInner>::new()),
state: RefCell::new(GutterState::new(fg)),
width: Cell::new(u32::MAX),
sign_method: Cell::new(None),
});
gutter.element.add_hooks(Hooks::UPDATE.union(Hooks::RENDER_AFTER));
gutter.element.set_layout(LayoutProperty::FlexShrink(0.0));
gutter
}

/// Resizes the gutter for the target's line count. Runs before every frame's layout.
/// Resizes the gutter for the target's line count and the width method. Runs before every frame's layout.
pub fn refresh(&self) {
if self.element.app().map(|app| app.width_method()) != self.sign_method.get() {
return self.measure_signs();
}
let lines = self.target.borrow().upgrade().and_then(|target| target.visible_lines());
let width = self.state.borrow().width(lines.map_or(1, |lines| lines.line_count.max(1)));
if self.width.replace(width) != width {
Expand All @@ -139,14 +144,15 @@ impl GutterInner {
/// Recomputes the sign widths after the signs changed.
pub fn measure_signs(&self) {
let Some(app) = self.element.app() else { return };
let context = app.session().context().clone();
let measure = |text: &str| context.text_width(text, app.width_method()).unwrap_or(0);
let (context, method) = (app.session().context().clone(), app.width_method());
let measure = |text: &str| context.text_width(text, method).unwrap_or(0);
let mut state = self.state.borrow_mut();
let widths = state.signs.values().fold((0, state.min_after_width), |(before, after), sign| {
(before.max(measure(&sign.before)), after.max(measure(&sign.after)))
});
state.sign_widths = widths;
drop(state);
self.sign_method.set(Some(method));
self.changed();
}

Expand Down
2 changes: 1 addition & 1 deletion packages/rust/crates/opentui/src/widget/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ impl Element {
/// nothing.
pub(crate) fn new(app: &App, kind: NodeKind, this: Weak<dyn Behavior>) -> Self {
let num = app.inner().allocate_num();
let node = app.report(Node::new(app.session(), kind, num));
let node = app.report(Node::new(app.synced_session(), kind, num));
Self {
app: Rc::downgrade(app.inner()),
node,
Expand Down
91 changes: 91 additions & 0 deletions packages/rust/crates/opentui/tests/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,97 @@ fn a_color_scheme_notice_lets_the_app_read_the_new_palette() {
client.finish().expect("the app thread").expect("the app");
}

// Expected: widgets, including a scrollback writer's, measure text with the width method native drawing uses, also
// after a reply changes it, as Core's `widthMethod` follows the renderer.
// Actual: `App::width_method` kept the method from before the reply, a scrollback writer's app kept it until its next
// render, and `NoZwj` was reported although native draws it as `Unicode`. Under ConPTY's DECRPM 2027 "unrecognized"
// reply, a ZWJ emoji measured 2 cells and drew 4: the table cell blanked it, the gutter sign was clipped, the input
// wrote over "💻", and a snapshot lost its wrapped row.
#[test]
fn widgets_measure_text_with_the_width_method_a_reply_switches_to() {
use opentui::split::{Scrollback, SnapshotOptions};
use opentui::widget::{LineNumbers, LineSign, WrapMode};
let zwj = "👩\u{200d}💻";
// An environment variable, the replies and keys, the text, whether the emulator clusters graphemes, the method
// native draws with, the text's cells under it, the link snapshot, and the screen rows to check. Native draws NoZwj
// as Unicode but the emulator splits the emoji, so only the method's row and the cursor show the app's measurement.
// Only Ghostty's reply turns hyperlinks on; "l" updates the link before anything else reads the terminal state.
let ghostty = &b"\x1b[?2027;2$y\x1bP>|ghostty 1.3.0\x1b\\lw"[..];
let cases = [
(("TERM", "xterm-256color"), &b"\x1b[?2027;0$yw"[..], zwj, false, "Wcwidth", 4, "go (https://a.b)", 0..5),
(("TERM_PROGRAM", "vscode"), b"\x1b[?2027;2$yw", zwj, true, "Unicode", 2, "go", 0..5),
(("TERM", "xterm-256color"), ghostty, "বাংলা", true, "UnicodeWide", 4, "go!", 0..5),
(("OPENTUI_FORCE_NOZWJ", "1"), b"w", zwj, true, "Unicode", 2, "go (https://a.b)", 2..3),
];
for (variable, input, text, clusters, method, cells, link, checked) in cases {
let environment = vec![("TERM".into(), "xterm-256color".into()), (variable.0.into(), variable.1.into())];
let options = RemoteOptions { width: 48, height: 5, environment };
let mut client = Client::start(options, quiet(), move |app| {
let editor = Textarea::new(app);
editor.set_text("x");
let gutter = LineNumbers::new(app, &editor).height(1).line_sign(0, LineSign::before(text, None));
let table = Table::new(app)
.set_columns([Column::new("").width(ColumnWidth::Cells(6)).align(Alignment::Right)])
.show_header(false)
.set_rows([[text]])
.size(6, 1);
let row = View::new(app).row().height(1).child(&table).child(&Text::new(app, "|"));
app.root().add(&row).add(&gutter);
// Made before the reply, as apps make their scrollback writer.
let scrollback = Scrollback::new(app).unwrap();
let link = Markdown::new(scrollback.app()).set_markdown("[go](https://a.b)");
app.on_key(move |cx, key| {
if key.matches("l") {
// Updates a paragraph without making a node, so only `hyperlinks` reads the terminal state.
link.append("!");
} else if key.matches("w") {
// Text and Markdown prose measure through the detached Session, Code through the app. Text comes
// first, before anything asks the app for its width method.
let line = format!("{text}abcd");
let shots = [
Text::new(scrollback.app(), &line).wrap(WrapMode::Char).as_any(),
Markdown::new(scrollback.app()).set_markdown(&line).as_any(),
Code::new(scrollback.app()).wrap(WrapMode::Char).set_code(&line).as_any(),
]
.map(|widget| {
let options = SnapshotOptions { width: Some(6), ..SnapshotOptions::default() };
let shot = scrollback.snapshot(&widget, options).unwrap().buffer.capture().unwrap().text();
shot.replace('\n', "/")
});
let link =
scrollback.snapshot(&link, SnapshotOptions::default()).unwrap().buffer.capture().unwrap();
let error = scrollback.app().session().context().last_error().unwrap();
let label = format!("m={:?} {} {error:?}", cx.app().width_method(), link.text().trim_end());
let label = Text::new(cx.app(), label);
cx.app().root().add(&label).add(&Text::new(cx.app(), shots.join(" ")));
} else if key.matches("i") {
let input = Input::new(cx.app()).set_value(format!("{text}yz"));
cx.app().root().add(&input);
input.focus();
}
});
});
client.wait_for("|");
client.send(input);
client.wait_for("m=");
client.send(b"i");
client.wait_for("yz");
let host = opentui::testing::TestApp::new(48, 5);
let output = if clusters { client.text() } else { client.text().replace("\x1b[?2027h", "") };
let screen = TerminalView::new(&host).size(48, 5).write(output).screen();
// A 6-cell snapshot wraps "cd" after a 4-cell text.
let (pad, shot) = (" ".repeat(6 - cells as usize), if cells == 4 { "ab/cd" } else { "abcd" });
let shots = vec![format!("{text}{shot}"); 3].join(" ");
// The label ends with the Context's last error: the snapshots leave none.
let rows = [format!("{pad}{text}|"), format!("{text} 1 x"), format!("m={method} {link} None"), shots];
let rows = [&rows[..], &[format!("{text}yz")]].concat();
let expected = (&rows[checked.clone()], Some((cells + 2, 4)));
assert_eq!((&screen.lines[checked], screen.cursor.position), expected, "{variable:?}");
client.link.terminate();
client.finish().expect("the app thread").expect("the app");
}
}

// Expected: an image drawn before the terminal answers the capability queries switches to Kitty graphics once
// Ghostty replies to XTVERSION and the Kitty graphics query, as Core repaints on each capability reply.
// Actual: a reply forced the next frame but did not ask for one, so an app with nothing else to draw kept its
Expand Down
Loading