diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 72df94b2bf..c94df50cd0 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -923,6 +923,7 @@ impl App { self.agents_overview.workspace.divider_drag_viewport = None; } } + self.transcript_view.bidi_layout = tui.terminal.bidi_layout; self.transcript_view.agent_links = self .side_retention_enabled(tui) .then(|| app_server.backend_id()); diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index b593110d70..f0a67a8b28 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -26,6 +26,7 @@ use crate::motion::MotionMode; use crate::pager_overlay::TranscriptHistoryState; use crate::sidebar_tab_strip::TabState; use crate::terminal_hyperlinks::HyperlinkLine; +use crate::terminal_hyperlinks::bidi; use crate::transcript_image::ImagePlacement; use crate::transcript_view::TranscriptView; use crate::transcript_view::ViewAction; @@ -234,8 +235,11 @@ impl App { chat_widget.active_cell_transcript_hyperlink_lines(width) }) } else if let Some(row) = live_summary { + let bidi_layout = view.bidi_layout; view.sync_live_layout(transcript_width, active_key, |width| { - Some(row.layout(width, expanded, chat_widget.active_auxiliary_lines(width))) + let lines = + bidi::session_lines(chat_widget.active_auxiliary_lines(width), bidi_layout); + Some(row.layout(width, expanded, lines)) }) } else { view.sync_live_activity_tail(transcript_width, active_key, expanded, |width| { @@ -394,6 +398,7 @@ impl App { id == panes.passive_thread && self.agent_navigation.is_parent_owned(id) }); if let Some(companion) = self.side_companions.get_mut(&panes.passive_thread) { + companion.view.bidi_layout = self.transcript_view.bidi_layout; companion.view.agent_links = self.transcript_view.agent_links; companion.view.image_protocol = self.transcript_view.image_protocol; panes.paint_companion( diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index c5cb7ab444..62d47e2eb5 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -13231,6 +13231,7 @@ async fn clear_only_ui_reset_preserves_chat_session_state() { crate::keymap::RuntimeKeymap::defaults().pager, /*copy_on_select*/ false, /*mouse_scroll_speed*/ 1.0, + /*bidi_layout*/ false, )); app.deferred_history_lines = vec![Line::from("stale buffered line").into()]; app.has_emitted_history_lines = true; diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index b982404997..05a354938d 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -215,6 +215,7 @@ impl App { .tui .mouse_scroll_speed .unwrap_or(/*default*/ 1.0), + tui.terminal.bidi_layout, ) .with_copy_on_select_clear_selection( self.local_settings.tui.copy_on_select_clear_selection, diff --git a/codex-rs/tui/src/clipboard_copy/worker_tests.rs b/codex-rs/tui/src/clipboard_copy/worker_tests.rs index f10d63ac37..f5eafc25fc 100644 --- a/codex-rs/tui/src/clipboard_copy/worker_tests.rs +++ b/codex-rs/tui/src/clipboard_copy/worker_tests.rs @@ -131,6 +131,7 @@ async fn blocked_copy_allows_overlay_exit_rejects_backlog_and_wakes_completion() RuntimeKeymap::defaults().pager, /*copy_on_select*/ false, /*mouse_scroll_speed*/ 1.0, + /*bidi_layout*/ false, ); overlay .handle_event( diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index 73733244fa..9f40e05f9f 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -61,8 +61,10 @@ impl Overlay { keymap: PagerKeymap, copy_on_select: bool, mouse_scroll_speed: f64, + bidi_layout: bool, ) -> Self { let mut overlay = TranscriptOverlay::new(cells, keymap); + overlay.view.bidi_layout = bidi_layout; overlay.view.copy_on_select = copy_on_select; overlay.view.mouse_scroll_speed = mouse_scroll_speed; overlay.view.primary_selection = crate::clipboard_copy::primary::available(); diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 0c806a0142..375d2641c0 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -781,6 +781,7 @@ async fn run_session_picker_event_loop( state.copy_on_select = options.copy_on_select; state.copy_on_select_clear_selection = options.copy_on_select_clear_selection; state.mouse_scroll_speed = options.mouse_scroll_speed; + state.bidi_layout = alt.tui.terminal.bidi_layout; state.density = options.initial_density; state.view_persistence = options.view_persistence; state.keymap = options.keymap; @@ -1148,6 +1149,7 @@ struct PickerState { copy_on_select: bool, copy_on_select_clear_selection: bool, mouse_scroll_speed: f64, + bidi_layout: bool, // Resolve local filesystem membership once per cwd for each page-loading cycle. local_cwd_matches: HashMap, requester: FrameRequester, @@ -1372,6 +1374,7 @@ impl PickerState { copy_on_select: false, copy_on_select_clear_selection: false, mouse_scroll_speed: 1.0, + bidi_layout: false, requester, relative_time_reference: None, pagination: PaginationState::new(), @@ -1524,6 +1527,7 @@ impl PickerState { self.keymap.pager.clone(), self.copy_on_select, self.mouse_scroll_speed, + self.bidi_layout, ) .with_copy_on_select_clear_selection(self.copy_on_select_clear_selection); if let Overlay::Transcript(view) = &mut overlay { @@ -5982,8 +5986,6 @@ mod tests { #[tokio::test] async fn loaded_transcript_waits_for_loading_frame_before_opening_overlay() { - use crate::history_cell::PlainHistoryCell; - let thread_id = ThreadId::new(); let (tx, mut receipts) = tokio::sync::mpsc::unbounded_channel(); let mut state = PickerState::new( @@ -6006,8 +6008,13 @@ mod tests { let owner = BackendId::new(); let key = (owner, thread_id); state.pending_transcript_open = Some(key); - let cells: TranscriptCells = - vec![Arc::new(PlainHistoryCell::new(vec!["transcript".into()]))]; + state.bidi_layout = true; + let cells: TranscriptCells = vec![Arc::new(crate::history_cell::new_user_prompt( + "transcript שלום".into(), + vec![], + vec![], + vec![], + ))]; state .transcript_cells @@ -6110,6 +6117,7 @@ mod tests { .iter() .map(ratatui::buffer::Cell::symbol) .collect::(); + assert!(text.contains("transcript םולש"), "{text}"); assert!(text.contains("BAtail"), "Find query: {text}"); state.overlay = None; @@ -6152,6 +6160,7 @@ mod tests { state.keymap.pager.clone(), state.copy_on_select, state.mouse_scroll_speed, + state.bidi_layout, )); let mut tui = crate::tui::test_support::make_test_tui().expect("tui"); state diff --git a/codex-rs/tui/src/terminal_hyperlinks/bidi.rs b/codex-rs/tui/src/terminal_hyperlinks/bidi.rs index e7ad02dfa5..071812a561 100644 --- a/codex-rs/tui/src/terminal_hyperlinks/bidi.rs +++ b/codex-rs/tui/src/terminal_hyperlinks/bidi.rs @@ -12,6 +12,7 @@ use icu_properties::CodePointMapData; use icu_properties::props::BidiMirroringGlyph; use ratatui::text::Line; use std::borrow::Cow; +use std::ops::Range; use std::sync::Arc; use unicode_bidi::BidiClass; use unicode_bidi::Level; @@ -26,6 +27,13 @@ pub(crate) fn prepare_message(lines: &mut [HyperlinkLine]) { } } +pub(crate) fn session_lines(mut lines: Vec, enabled: bool) -> Vec { + if enabled { + resolve_paragraphs(&mut lines); + } + lines +} + pub(crate) fn resolve_paragraphs(lines: &mut [HyperlinkLine]) { for group in lines.chunk_by_mut(|a, b| { matches!( @@ -77,6 +85,12 @@ pub(crate) fn resolve_paragraphs(lines: &mut [HyperlinkLine]) { } } +/// A projected row and the logical body bytes under each of its visible body cells. +pub(crate) struct VisualRow { + pub(crate) line: HyperlinkLine, + pub(crate) offsets: Vec>, +} + pub(crate) fn paint_rows(lines: &mut [HyperlinkLine], width: usize) { resolve_paragraphs(lines); for line in lines { @@ -85,12 +99,12 @@ pub(crate) fn paint_rows(lines: &mut [HyperlinkLine], width: usize) { && let Some(levels) = levels.get(source.range.clone()) && let Some(visual) = project(line, levels, width) { - *line = visual; + *line = visual.line; } } } -fn project(line: &HyperlinkLine, levels: &[Level], width: usize) -> Option { +pub(crate) fn project(line: &HyperlinkLine, levels: &[Level], width: usize) -> Option { let source = line.source.as_ref()?; // Never reorder across terminal autowrap boundaries (e.g. an oversized URL). if line.width() > width || levels.len() != source.range.len() { @@ -130,14 +144,15 @@ fn project(line: &HyperlinkLine, levels: &[Level], width: usize) -> Option Option, + pub(crate) bidi_layout: bool, pub(crate) agent_links: Option, pub(crate) document_links: bool, pub(crate) mouse_scroll_speed: f64, @@ -140,6 +142,7 @@ impl Default for TranscriptView { fn default() -> Self { Self { image_protocol: None, + bidi_layout: false, agent_links: None, document_links: false, mouse_scroll_speed: 1.0, @@ -523,8 +526,10 @@ impl TranscriptView { if self.detailed { self.sync_live_tail(width, /*key*/ None, lines); } else if let Some(row) = summary { + let bidi_layout = self.bidi_layout; self.sync_live_layout(width, /*key*/ None, |width| { - Some(row.layout(width, expanded, auxiliary.to_vec())) + let lines = bidi::session_lines(auxiliary.to_vec(), bidi_layout); + Some(row.layout(width, expanded, lines)) }); } else { self.sync_live_activity_tail(width, /*key*/ None, expanded && disclose, |width| { @@ -569,8 +574,10 @@ impl TranscriptView { key: Option, lines: impl FnOnce(u16) -> Option>, ) -> bool { + let bidi_layout = self.bidi_layout; self.sync_live_layout(width, key, |width| { - lines(width).map(|lines| TextLayout::new(lines, width)) + lines(width) + .map(|lines| TextLayout::new(bidi::session_lines(lines, bidi_layout), width)) }) } @@ -585,8 +592,10 @@ impl TranscriptView { .disclosure .keymap .primary_hint(crate::keymap::KeymapContext::Global, "open_transcript"); + let bidi_layout = self.bidi_layout; self.sync_live_layout(width, key, |width| { - lines(width).map(|lines| layout::activity_layout(lines, width, expanded, shortcut)) + lines(width) + .map(|lines| layout::activity_layout(lines, width, expanded, bidi_layout, shortcut)) }) } diff --git a/codex-rs/tui/src/transcript_view/input.rs b/codex-rs/tui/src/transcript_view/input.rs index e5ef02ed65..9d0a359cf3 100644 --- a/codex-rs/tui/src/transcript_view/input.rs +++ b/codex-rs/tui/src/transcript_view/input.rs @@ -326,6 +326,15 @@ impl TranscriptView { if modifiers == KeyModifiers::CONTROL && code == KeyCode::Char(' ') { self.begin_selection(cells, self.area.x, self.area.y, /*clicks*/ 1); if let Some(selection) = &mut self.selection { + // Ctrl+Space extends a half-open source range with the arrow keys. + // Start at the logical boundary even if the leftmost glyph is RTL. + if let Some(first) = self.visible.first() + && first.layout.visual_hit(first.row, /*column*/ 0).is_some() + { + let mut anchor = selection.start; + anchor.offset = first.layout.position_at(first.row, /*column*/ 0); + selection.set_keyboard_range(anchor, anchor); + } selection.dragging = false; selection.resume_on_empty = false; } @@ -367,6 +376,7 @@ impl TranscriptView { selection.end, selection.unit(), selection.has_table_scope(), + selection.mouse_endpoints, ) }); let action = @@ -377,6 +387,7 @@ impl TranscriptView { selection.end, selection.unit(), selection.has_table_scope(), + selection.mouse_endpoints, ) }); if endpoint_changed && before != after { diff --git a/codex-rs/tui/src/transcript_view/layout.rs b/codex-rs/tui/src/transcript_view/layout.rs index 4966c4cda1..d3718de333 100644 --- a/codex-rs/tui/src/transcript_view/layout.rs +++ b/codex-rs/tui/src/transcript_view/layout.rs @@ -25,13 +25,14 @@ pub(super) fn activity_layout( mut lines: ActivityTranscriptLines, width: u16, expanded: bool, + bidi_layout: bool, shortcut: Option, ) -> TextLayout { let has_details = !lines.activity.is_empty() && (expanded || lines.disclosure.is_some()); let source_offset = (!lines.auxiliary.is_empty()) .then(|| TextLayout::new(lines.activity.clone(), width).text().len()); lines.activity.extend(lines.auxiliary); - let layout = TextLayout::new(lines.activity, width); + let layout = TextLayout::new(bidi::session_lines(lines.activity, bidi_layout), width); if !has_details { return layout; } @@ -78,13 +79,13 @@ fn cell_content_layout( }, width, presentation.expanded, + presentation.bidi_layout, shortcut, ) } else { - TextLayout::new( - crate::history_cell::fullscreen_session_lines(cell, width, presentation.detailed, mode), - width, - ) + let lines = + crate::history_cell::fullscreen_session_lines(cell, width, presentation.detailed, mode); + TextLayout::new(bidi::session_lines(lines, presentation.bidi_layout), width) }; if let Some(protocol) = presentation.image_protocol && let Some(path) = cell.image_path() @@ -143,6 +144,7 @@ pub(super) struct CellPresentation { shares_prompt_background: bool, turn_tip_space: bool, expanded: bool, + bidi_layout: bool, disclosure: bool, detailed: bool, image_protocol: Option, @@ -163,6 +165,7 @@ impl TranscriptView { self.disclosure.expanded.extend(ids); } CellPresentation { + bidi_layout: self.bidi_layout, summarized: false, separated: false, shares_prompt_background: false, @@ -439,6 +442,7 @@ impl LayoutCache { fn evict(&mut self) { let retained_bytes = |entry: &CachedLayout| { entry.layout.text().len() + + entry.layout.mapping_bytes + entry .layout .image diff --git a/codex-rs/tui/src/transcript_view/layout_tests.rs b/codex-rs/tui/src/transcript_view/layout_tests.rs index 6f9f0d4e7d..326b0708ee 100644 --- a/codex-rs/tui/src/transcript_view/layout_tests.rs +++ b/codex-rs/tui/src/transcript_view/layout_tests.rs @@ -46,6 +46,7 @@ fn layouts_refresh_for_width_animation_and_mutable_frames() { &history, width, CellPresentation { + bidi_layout: false, summarized: false, separated: false, shares_prompt_background: false, @@ -105,6 +106,7 @@ fn recent_entries_are_reused_and_old_entries_are_evicted() { &history, /*width*/ 20, CellPresentation { + bidi_layout: false, summarized: false, separated: false, shares_prompt_background: false, @@ -128,6 +130,7 @@ fn recent_entries_are_reused_and_old_entries_are_evicted() { &history, /*width*/ 20, CellPresentation { + bidi_layout: false, summarized: false, separated: false, shares_prompt_background: false, diff --git a/codex-rs/tui/src/transcript_view/search_presentation.rs b/codex-rs/tui/src/transcript_view/search_presentation.rs index 912d2a0e9f..81136c0a32 100644 --- a/codex-rs/tui/src/transcript_view/search_presentation.rs +++ b/codex-rs/tui/src/transcript_view/search_presentation.rs @@ -69,7 +69,10 @@ impl TranscriptView { return false; } self.search.live_key = next; - let live = lines(width).map(|lines| Arc::new(TextLayout::new(lines, width))); + let live = lines(width).map(|lines| { + let lines = bidi::session_lines(lines, self.bidi_layout); + Arc::new(TextLayout::new(lines, width)) + }); let changed = self.search.live.as_ref().map(|layout| layout.text()) != live.as_ref().map(|layout| layout.text()); if changed { diff --git a/codex-rs/tui/src/transcript_view/select_mode.rs b/codex-rs/tui/src/transcript_view/select_mode.rs index e64f444a4e..ee2fb18d1c 100644 --- a/codex-rs/tui/src/transcript_view/select_mode.rs +++ b/codex-rs/tui/src/transcript_view/select_mode.rs @@ -413,7 +413,18 @@ impl TranscriptView { Scope::Block(block) => block.swap(), } mode.preferred_column = None; + // A mouse sweep can include bytes beyond both pointer glyphs. Swapping + // changes which endpoint moves, but only motion should resize the range. + let swept = self + .selection + .as_ref() + .and_then(|s| s.mouse_endpoints.map(|(a, b)| (s.end, s.start, (b, a)))); self.sync_select_range(cells); + if let (Some(selection), Some((start, end, pointers))) = (&mut self.selection, swept) { + selection.start = start; + selection.end = end; + selection.mouse_endpoints = Some(pointers); + } self.reveal_select_cursor(cells); } @@ -511,9 +522,16 @@ impl TranscriptView { return; }; let (start, end, unit) = (selection.start, selection.end, selection.unit()); + let mouse_endpoints = selection.mouse_endpoints; let snapshot = self.snapshot_cells(); let cells = snapshot.as_deref().unwrap_or_default(); let mark = has_range.then(|| { + if let Some((anchor, active)) = mouse_endpoints { + return Mark { + active, + ..Mark::at(anchor, unit) + }; + } if self.anchor_order(cells, start) <= self.anchor_order(cells, end) { let active = self.before_grapheme(cells, end); let anchor_end = self diff --git a/codex-rs/tui/src/transcript_view/selection.rs b/codex-rs/tui/src/transcript_view/selection.rs index f89eb29d24..b020bd809c 100644 --- a/codex-rs/tui/src/transcript_view/selection.rs +++ b/codex-rs/tui/src/transcript_view/selection.rs @@ -115,8 +115,11 @@ pub(super) struct Selection { pub(super) moved: bool, moved_vertically: bool, pointer_origin_row: u16, + origin_margin: Option, pub(super) resume_on_empty: bool, pub(super) pointer: Option, + /// Pointer endpoints before a bidi sweep expands the contiguous copy range. + pub(super) mouse_endpoints: Option<(Anchor, Anchor)>, pub(super) pressed_link: Option, origin: (Anchor, Anchor), table_cell: Option, @@ -136,7 +139,9 @@ impl Selection { moved: true, moved_vertically: false, pointer_origin_row: 0, + origin_margin: None, resume_on_empty: false, + mouse_endpoints: None, pointer: None, pressed_link: None, origin: (cursor, cursor), @@ -164,7 +169,9 @@ impl Selection { } self.start = start; self.end = end; + self.mouse_endpoints = None; self.origin = (start, end); + self.origin_margin = None; self.preferred_column = None; } @@ -231,6 +238,28 @@ impl Selection { self.unit = unit; } + /// Include each painted glyph crossed by a mouse drag. + fn include_swept_glyphs(&mut self) { + let (mut first, mut last) = (&mut self.start, &mut self.end); + if (first.index, first.offset) > (last.index, last.offset) { + std::mem::swap(&mut first, &mut last); + } + let same = first.key == last.key; + if let Some(layout) = self.snapshot.pinned.get(&first.key) { + let range = layout.visual_selection(Some(first.offset), same.then_some(last.offset)); + first.offset = range.start; + if same { + last.offset = range.end; + return; + } + } + if let Some(layout) = self.snapshot.pinned.get(&last.key) { + last.offset = layout + .visual_selection(/*start*/ None, Some(last.offset)) + .end; + } + } + pub(super) fn unit(&self) -> SelectionUnit { self.unit } @@ -274,7 +303,9 @@ impl TranscriptView { moved: false, moved_vertically: false, pointer_origin_row: 0, + origin_margin: None, resume_on_empty: false, + mouse_endpoints: None, pointer: None, pressed_link: None, origin: (start, end), @@ -293,11 +324,11 @@ impl TranscriptView { clicks: u8, ) { self.copy_mode = None; - let Some((anchor, layout, layout_row)) = self.hit_test(column, row) else { + let unit = SelectionUnit::from_clicks(clicks); + let Some((anchor, layout, layout_row, range)) = self.hit_test(column, row, unit) else { return; }; self.cancel_beginning(); - let unit = SelectionUnit::from_clicks(clicks); let table_cell = if self.select_mode.is_none() && matches!(clicks, 1 | 3) && let Some(cell) = layout.table_cell_at( @@ -320,7 +351,7 @@ impl TranscriptView { Some(table) => { layout.table_cell_pointer_range(&table.ranges, layout_row, anchor.offset) } - None => unit.range(layout.text(), anchor.offset), + None => range, }; let snapshot = self.capture_snapshot(cells); self.held_reading = None; @@ -347,7 +378,9 @@ impl TranscriptView { moved: false, moved_vertically: false, pointer_origin_row: row, + origin_margin: layout.visual_margin(layout_row, column.saturating_sub(self.area.x)), resume_on_empty: was_following, + mouse_endpoints: None, pointer: Some(ScreenPosition::new(column, row)), pressed_link: None, }); @@ -405,7 +438,11 @@ impl TranscriptView { } pub(super) fn extend_selection(&mut self, column: u16, row: u16) { - let Some((end, layout, layout_row)) = self.hit_test(column, row) else { + let Some(selection) = &self.selection else { + return; + }; + let Some((end, layout, layout_row, range)) = self.hit_test(column, row, selection.unit) + else { return; }; let Some(mut selection) = self.selection.take() else { @@ -437,10 +474,17 @@ impl TranscriptView { } selection.clear_table_cell_scope(); let origin = selection.origin; - let range = selection.unit.range(layout.text(), end.offset); - selection.snapshot.pinned.entry(end.key).or_insert(layout); + if selection.unit == SelectionUnit::Character + && origin.0 == end + && selection.origin_margin.is_some() + && selection.origin_margin + == layout.visual_margin(layout_row, column.saturating_sub(self.area.x)) + { + return (end, end); + } let backwards = (self.resolve(&cells, end), end.offset) < (self.resolve(&cells, origin.0), origin.0.offset); + selection.snapshot.pinned.entry(end.key).or_insert(layout); ( if backwards { origin.1 } else { origin.0 }, Anchor { @@ -454,6 +498,12 @@ impl TranscriptView { selection.pointer = Some(ScreenPosition::new(column, row)); selection.preferred_column = None; self.pin_selection_range(&cells, &mut selection); + let bounds = (selection.start, selection.end); + if selection.table_cell.is_none() && selection.unit != SelectionUnit::Line { + selection.include_swept_glyphs(); + } + selection.mouse_endpoints = + (bounds != (selection.start, selection.end)).then_some((selection.origin.0, end)); if previous != (selection.start, selection.end) || previous_head != table_head(&selection) { selection.primary_owner = None; selection.pending_copy = None; @@ -833,6 +883,7 @@ impl TranscriptView { if selection.end != next { selection.primary_owner = None; } + selection.mouse_endpoints = None; selection.end = next; selection.dragging = false; selection.preferred_column = column; @@ -973,22 +1024,36 @@ impl TranscriptView { } } - fn hit_test(&self, column: u16, row: u16) -> Option<(Anchor, Arc, usize)> { + fn hit_test( + &self, + column: u16, + row: u16, + unit: SelectionUnit, + ) -> Option<(Anchor, Arc, usize, Range)> { let row = row.saturating_sub(self.area.y) as usize; let visible = self .visible .get(row.min(self.visible.len().saturating_sub(/*rhs*/ 1)))?; + let column = column.saturating_sub(self.area.x); + let hit = visible.layout.visual_hit(visible.row, column); + let offset = hit.as_ref().map_or_else( + || visible.layout.position_at(visible.row, column), + |bytes| bytes.start, + ); + let range = match hit { + Some(bytes) if unit == SelectionUnit::Character => bytes, + _ => unit.range(visible.layout.text(), offset), + }; Some(( Anchor { key: visible.key, index: visible.index, - offset: visible - .layout - .position_at(visible.row, column.saturating_sub(self.area.x)), + offset, row_bias: 0, }, Arc::clone(&visible.layout), visible.row, + range, )) } @@ -1045,13 +1110,17 @@ impl TranscriptView { let row = layout .row_for_offset(offset) .saturating_add_signed(end.row_bias.saturating_neg()); - let (next, row) = self.move_rows(cells, index, row, direction); + let target = self.move_rows(cells, index, row, direction); + if target == (index, row) { + return Some(end); + } + let (next, row) = target; index = next; let next_layout = self.layout(cells, index)?; - let offset = next_layout.position_at( - row, - preferred_column.unwrap_or_else(|| layout.column_for_offset(offset)), - ); + let column = preferred_column.unwrap_or_else(|| layout.column_for_offset(offset)); + let offset = next_layout + .visual_hit(row, column) + .map_or_else(|| next_layout.position_at(row, column), |bytes| bytes.start); row_bias = next_layout.row_for_offset(offset) as isize - row as isize; offset } diff --git a/codex-rs/tui/src/transcript_view/selection_tests.rs b/codex-rs/tui/src/transcript_view/selection_tests.rs index 17ef0b03e3..70e0c55d17 100644 --- a/codex-rs/tui/src/transcript_view/selection_tests.rs +++ b/codex-rs/tui/src/transcript_view/selection_tests.rs @@ -18,6 +18,85 @@ use crossterm::event::MouseEventKind; use pretty_assertions::assert_eq; use std::time::Instant; +fn rtl_view(cells: &[Arc]) -> (TranscriptView, String) { + let mut view = TranscriptView { + bidi_layout: true, + ..Default::default() + }; + let painted = render(&mut view, cells, /*width*/ 20, /*height*/ 2); + (view, painted) +} + +#[test] +fn rtl_transcript_keyboard_crosses_original_mouse_anchor() { + let cell = AgentMarkdownCell::new("A אבג B".into(), std::path::Path::new(".")); + let cells: Vec> = vec![Arc::new(cell)]; + let (mut view, painted) = rtl_view(&cells); + let column = |ch| painted.chars().position(|c| c == ch).unwrap() as u16; + let margin = view.area.width - 2; + view.begin_selection(&cells, margin, /*row*/ 0, /*clicks*/ 1); + view.extend_selection(margin + 1, /*row*/ 0); + assert_eq!(view.selected_text(&cells), None); + view.begin_selection(&cells, column('ג'), /*row*/ 0, /*clicks*/ 1); + view.extend_selection(column('B'), /*row*/ 0); + assert!(view.begin_select_mode(&cells)); + for _ in 0..2 { + view.handle_key(KeyCode::Char('o').into(), &cells); + assert_eq!(view.selected_text(&cells).as_deref(), Some("אבג B")); + } + for _ in 0..3 { + view.handle_key(KeyCode::Left.into(), &cells); + } + assert_eq!(view.selected_text(&cells).as_deref(), Some("בג")); +} + +#[test] +fn rtl_transcript_keyboard_selection_is_logical_and_mouse_selection_is_visual() { + let text = "אבג Codex Two זחט"; + let cell = AgentMarkdownCell::new(format!("דהו \n{text}"), std::path::Path::new(".")); + let cells: Vec> = vec![Arc::new(cell)]; + let (mut view, painted) = rtl_view(&cells); + let line = painted.lines().last().unwrap(); + let column = |ch| line.chars().position(|c| c == ch).unwrap() as u16; + assert!(view.begin_select_mode(&cells)); + // Right advances in source order through the Hebrew word. + view.handle_key(KeyCode::Char('v').into(), &cells); + for _ in 0..2 { + view.handle_key(KeyCode::Right.into(), &cells); + } + assert_eq!(view.selected_text(&cells).as_deref(), Some("אבג")); + let (mut view, _) = rtl_view(&cells); + view.begin_selection(&cells, column('ט'), /*row*/ 1, /*clicks*/ 2); + view.extend_selection(column('T'), /*row*/ 1); + assert_eq!(view.selected_text(&cells).as_deref(), Some("Codex Two זחט")); + + view.begin_selection(&cells, column('ט'), /*row*/ 1, /*clicks*/ 1); + view.extend_selection(column('T'), /*row*/ 1); + assert!(view.begin_select_mode(&cells)); + let mode = view.select_mode.unwrap(); + let cursor = mode.cursor(view.selection.as_ref().unwrap()); + assert_eq!(cursor.offset, "דהו\nאבג Codex ".len()); + let (mut view, _) = rtl_view(&cells); + view.begin_selection(&cells, /*column*/ 0, /*row*/ 0, /*clicks*/ 1); + view.extend_selection(view.area.width - 1, /*row*/ 0); + let selection = view.selection.as_ref().unwrap(); + let end = std::cmp::max_by_key(selection.start, selection.end, |a| a.offset); + assert_eq!( + view.move_selection_endpoint(&cells, end, KeyCode::Up, /*preferred_column*/ None), + Some(end) + ); + for (start, end, expected) in [ + ((column('ט'), 1), (view.area.width - 1, 1), text), + ((column('א'), 1), (0, 1), text), + ((0, 0), (column('א'), 1), "דהו\nאבג Codex Two זחט"), + ((column('א'), 1), (0, 0), "דהו\nאבג Codex Two זחט"), + ] { + view.begin_selection(&cells, start.0, start.1, /*clicks*/ 1); + view.extend_selection(end.0, end.1); + assert_eq!(view.selected_text(&cells).as_deref(), Some(expected)); + } +} + #[test] fn selection_highlights_hard_breaks_within_and_between_entries() { let mut frames = Vec::new(); diff --git a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__text__tests__rtl_transcript_reflow_keeps_link_hits_highlights_and_copy_logical.snap b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__text__tests__rtl_transcript_reflow_keeps_link_hits_highlights_and_copy_logical.snap new file mode 100644 index 0000000000..e5654afb25 --- /dev/null +++ b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__text__tests__rtl_transcript_reflow_keeps_link_hits_highlights_and_copy_logical.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/transcript_view/text_tests.rs +expression: "snapshots.join(\"\\n\")" +--- +• «مكب» file.rs 123 مالَسَ + שלום עולם +• مالَسَ + file.rs + «مكب» 123 + שלום + עולם diff --git a/codex-rs/tui/src/transcript_view/text.rs b/codex-rs/tui/src/transcript_view/text.rs index 637fa82f68..98fe439fc4 100644 --- a/codex-rs/tui/src/transcript_view/text.rs +++ b/codex-rs/tui/src/transcript_view/text.rs @@ -36,6 +36,7 @@ use crate::terminal_hyperlinks::LineWrapPolicy; use crate::terminal_hyperlinks::LogicalLineSource; use crate::terminal_hyperlinks::ReaderLink; use crate::terminal_hyperlinks::TerminalHyperlink; +use crate::terminal_hyperlinks::bidi; use crate::terminal_hyperlinks::remap_source_wrapped_line; use crate::width::display_width; use crate::wrapping::RtOptions; @@ -54,6 +55,7 @@ pub(crate) struct TextLayout { logical: Vec, text: String, rows: Vec, + pub(super) mapping_bytes: usize, pub(super) width: u16, pub(super) separated: bool, pub(super) disclosure: bool, @@ -74,6 +76,7 @@ struct DisclosureControl { } struct TextRow { + visual: Option>, line: HyperlinkLine, source: Range, /// Source offset at the logical line end; absent on soft wraps and synthetic rows. @@ -85,6 +88,14 @@ struct TextRow { tabs: tabs::TabStops, } +impl TextRow { + fn painted_line(&self) -> &HyperlinkLine { + self.visual + .as_ref() + .map_or(&self.line, |visual| &visual.line) + } +} + pub(super) struct TableCellHit { table: Arc<[&'static str]>, pub(super) endpoint: TableEndpoint, @@ -366,6 +377,7 @@ impl TextLayout { self.rows.insert( index, TextRow { + visual: None, line: HyperlinkLine::from(line), source: offset..offset, line_end: None, @@ -707,8 +719,11 @@ impl TextLayout { Rect::new(area.x, area.y + screen_row, area.width, /*height*/ 1); buf.set_style(row_area, row.line.line.style); row_area.width = row.content_width; - HyperlinkParagraph::new(std::slice::from_ref(&row.line), row.line.line.style) - .render(row_area, buf); + HyperlinkParagraph::new( + std::slice::from_ref(row.painted_line()), + row.line.line.style, + ) + .render(row_area, buf); } } @@ -729,8 +744,74 @@ impl TextLayout { row.source.end } + pub(super) fn visual_margin(&self, row: usize, column: u16) -> Option { + let row = self.rows.get(row)?; + let width = row.visual.as_ref()?.offsets.len(); + let column = usize::from(column); + if column < row.first_column { + Some(Alignment::Left) + } else { + (column >= row.first_column + width).then_some(Alignment::Right) + } + } + + /// A reordered row has no single logical boundary between adjacent visual runs. + /// Include both endpoint graphemes on drag, clamping padding to the nearest glyph. + pub(super) fn visual_hit(&self, row: usize, column: u16) -> Option> { + let row = self.rows.get(row)?; + let offsets = &row.visual.as_ref()?.offsets; + let column = usize::from(column).saturating_sub(row.first_column); + let bytes = offsets.get(column).or_else(|| offsets.last())?; + Some(row.source.start + bytes.start..row.source.start + bytes.end) + } + + /// Selection is contiguous in source order. At a direction change the glyphs + /// between the endpoints can extend beyond both endpoints in the source. + /// Missing endpoints lie in a different entry. On different rows the sweep + /// extends to the right edge of the first row and from the left edge of the last. + pub(super) fn visual_selection( + &self, + start: Option, + end: Option, + ) -> Range { + let mut range = start.unwrap_or(0)..end.unwrap_or(self.text.len()); + if range.is_empty() { + return range; + } + let last = end.and_then(|end| end.checked_sub(1)); + let swept = |offset| { + let row = self.rows.get(self.row_for_offset(offset))?; + let offsets = &row.visual.as_ref()?.offsets; + let column = |offset: usize| { + let offset = offset.checked_sub(row.source.start)?; + offsets.iter().position(|bytes| bytes.contains(&offset)) + }; + let from = start.and_then(column).unwrap_or(0); + let to = last + .and_then(column) + .unwrap_or(offsets.len().checked_sub(1)?); + let cells = &offsets[from.min(to)..=from.max(to)]; + if cells.len() == offsets.len() { + return Some(row.source.clone()); + } + let start = cells.iter().map(|bytes| bytes.start).min()?; + let end = cells.iter().map(|bytes| bytes.end).max()?; + Some(row.source.start + start..row.source.start + end) + }; + if let Some(first) = start.and_then(swept) { + range.start = range.start.min(first.start); + } + if let Some(last) = last.and_then(swept) { + range.end = range.end.max(last.end); + } + range + } + /// Resolve a keyboard caret to a grapheme start while leaving truly empty rows blank. pub(super) fn cursor_position_at(&self, row: usize, column: u16) -> usize { + if let Some(bytes) = self.visual_hit(row, column) { + return bytes.start; + } let offset = self.position_at(row, column); let Some(row) = self.rows.get(row) else { return offset; @@ -811,6 +892,14 @@ impl TextLayout { let offset = self .text .floor_char_boundary(offset.clamp(row.source.start, row.source.end)); + if let Some(visual) = &row.visual { + let column = visual + .offsets + .iter() + .position(|bytes| bytes.contains(&(offset - row.source.start))) + .unwrap_or(visual.offsets.len()); + return (row.first_column + column).min(usize::from(self.width)) as u16; + } let column = row.first_column + row.tabs.column_for_offset( display_width(&self.text[row.source.start..offset]), @@ -828,6 +917,19 @@ impl TextLayout { start_row: usize, ) { for (screen_row, row) in self.visible_rows(area, start_row) { + if let Some(visual) = &row.visual { + for (column, bytes) in visual.offsets.iter().enumerate() { + let x = row.first_column + column; + if x < usize::from(row.content_width) + && row.source.start + bytes.start < range.end + && row.source.start + bytes.end > range.start + { + buf[(area.x + x as u16, area.y + screen_row)] + .set_style(Style::default().add_modifier(Modifier::REVERSED)); + } + } + continue; + } let mut column = row.first_column; for (offset, grapheme) in self.text[row.source.clone()].grapheme_indices(/*is_extended*/ true) @@ -953,7 +1055,10 @@ impl TextLayout { pub(super) fn row_links(&self, row: usize) -> Option<(usize, &[TerminalHyperlink])> { let row = self.rows.get(row)?; - Some((row.first_column - row.prefix_columns, &row.line.hyperlinks)) + Some(( + row.first_column - row.prefix_columns, + &row.painted_line().hyperlinks, + )) } fn visible_rows(&self, area: Rect, start_row: usize) -> impl Iterator { @@ -994,6 +1099,11 @@ impl TextLayout { image_left_aligned: false, logical, text, + mapping_bytes: rows + .iter() + .filter_map(|row| row.visual.as_ref()) + .map(|row| row.offsets.capacity() * size_of::>()) + .sum(), rows, width, separated: false, @@ -1080,7 +1190,16 @@ fn layout_line(logical: &LogicalLine, text_start: usize, width: u16) -> Vec columns.saturating_sub(text_width), }; let range = text_start + source.start..text_start + source.end; + let visual = logical.origin.bidi.as_ref().and_then(|levels| { + let start = logical.origin.range.start; + bidi::project( + &wrapped, + levels.get(start + source.start..start + source.end)?, + columns, + ) + }); TextRow { + visual: visual.map(Box::new), line: wrapped, source: range, line_end: None, diff --git a/codex-rs/tui/src/transcript_view/text_tests.rs b/codex-rs/tui/src/transcript_view/text_tests.rs index c666173c43..c5163b8e3a 100644 --- a/codex-rs/tui/src/transcript_view/text_tests.rs +++ b/codex-rs/tui/src/transcript_view/text_tests.rs @@ -482,6 +482,58 @@ fn document_link_navigation_preserves_occurrences_across_wraps() { } } +#[test] +fn rtl_transcript_reflow_keeps_link_hits_highlights_and_copy_logical() { + use crate::terminal_hyperlinks::TerminalHyperlink; + use crate::terminal_hyperlinks::bidi; + + let text = "سَلَام file.rs 123 «بكم»"; + let mut line = HyperlinkLine::from(text); + // The link crosses a direction change and occupies two separate visual ranges. + let destination = "https://example.org"; + line.hyperlinks + .push(TerminalHyperlink::web(2..9, destination.into())); + let tabbed = "\tשלום עולם"; + let mut lines = prefix_hyperlink_lines(vec![line, tabbed.into()], "• ".dim(), " ".into()); + bidi::prepare_message(&mut lines); + bidi::resolve_paragraphs(&mut lines); + let wide = TextLayout::new(lines, /*width*/ 40); + let narrow = wide.rewrap(/*width*/ 12); + let mut snapshots = Vec::new(); + for layout in [&wide, &narrow] { + assert_eq!(layout.text(), format!("{text}\n{tabbed}")); + let area = Rect::new( + /*x*/ 0, + /*y*/ 0, + layout.width, + layout.row_count() as u16, + ); + let mut buf = Buffer::empty(area); + layout.render(area, &mut buf, /*start_row*/ 0); + let range = text.find('ا').unwrap()..text.find('.').unwrap(); + layout.highlight(range.clone(), area, &mut buf, /*start_row*/ 0); + for (row, line) in layout.rows.iter().enumerate() { + let mut rendered = String::new(); + for col in 0..area.width { + let cell = &buf[(col, row as u16)]; + let offset = layout.cursor_position_at(row, col); + let linked = range.contains(&offset) + && col >= 2 + && usize::from(col) < line.painted_line().width(); + assert_eq!(layout.raw_link_at(row, col).is_some(), linked); + assert_eq!(cell.modifier.contains(Modifier::REVERSED), linked); + if linked { + assert_eq!(layout.column_for_offset(offset), col); + assert!(cell.symbol().contains(destination)); + } + rendered.push_str(&crate::terminal_hyperlinks::strip_osc8(cell.symbol())); + } + snapshots.push(rendered.trim_end().to_string()); + } + } + insta::assert_snapshot!(snapshots.join("\n")); +} + #[test] fn rtl_transcript_preserves_command_boundaries() { use crate::terminal_hyperlinks::bidi;