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
1 change: 1 addition & 0 deletions docs/learning-rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ cargo test # 跑测试
| Enter / Shift+Enter(或 Ctrl+J) | 发送 / 换行 |
| Alt+Enter | 排进队列,当前任务完成后再发(follow-up) |
| Ctrl+V / Ctrl+Y | 从剪贴板粘贴(图片、文件路径或文本)/ 复制最后一条回复 |
| 鼠标拖动 | 选中文字,松开即复制到剪贴板(终端原生选择:按住 Shift 拖动,或 `/mouse` 关闭鼠标捕获) |
| Ctrl+G | 子代理面板(任务板 + 选中任务的记录) |
| Esc、Ctrl+C | 打断当前回合;空闲时连按两次 Ctrl+C 退出 |
| agent 忙时按 Enter | 把消息排进队列,作为“插话”发给 agent |
Expand Down
97 changes: 89 additions & 8 deletions src/tui/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ use crate::integrations::{Reporters, State, TurnOutcome};
use std::sync::Arc;
use std::time::Instant;

use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent, MouseEventKind};
use crossterm::event::{
KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use ratatui::layout::{Margin, Position, Rect};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
Expand All @@ -15,6 +18,7 @@ use super::fx::Fx;
use super::game2048::{Dir, Game};
use super::input::Input;
use super::paste::{self, PasteStore};
use super::select::Selection;
use super::theme::{self, THEMES, Theme};
use crate::agent::{Agent, AgentEvent, EventTx, FOLLOW_UP, STEER, SteerQueue};
use crate::background::BackgroundEvent;
Expand Down Expand Up @@ -236,7 +240,7 @@ pub const COMMANDS: &[SlashCommand] = &[
SlashCommand {
name: "mouse",
args: "",
help: "切换鼠标捕获(关闭后可用终端原生选择复制)",
help: "切换鼠标捕获(开:拖动选择自动复制;关:终端原生选择)",
},
SlashCommand {
name: "clear",
Expand Down Expand Up @@ -279,6 +283,12 @@ pub struct App {
last_ctrl_c: Option<Instant>,
pub mouse_capture: bool,
pub mouse_changed: bool,
/// Mouse text selection (drawn reversed; copied on release).
pub selection: Option<Selection>,
/// A drag is in progress.
selecting: bool,
/// The next frame reads the selection's text back for copying.
pub copy_selection: bool,
pub toast: Option<(String, Instant)>,
pub skills: Vec<Skill>,
/// Workdir and daily flag the skills were discovered for (the agent is
Expand Down Expand Up @@ -375,6 +385,9 @@ impl App {
last_ctrl_c: None,
mouse_capture: true,
mouse_changed: false,
selection: None,
selecting: false,
copy_selection: false,
toast: None,
skills,
skills_scope,
Expand Down Expand Up @@ -1058,18 +1071,83 @@ impl App {
self.toast("还没有可复制的回复");
return;
};
if clipboard::write_text(&text) {
self.toast("已复制最后一条回复");
self.copy_text(&text, "已复制最后一条回复");
}

/// Copy text with the native tool, else OSC 52.
fn copy_text(&mut self, text: &str, done: &str) {
if clipboard::write_text(text) {
self.toast(done.to_string());
} else {
self.pending_osc52 = Some(clipboard::osc52(&text));
self.toast("已通过终端(OSC 52)复制");
self.pending_osc52 = Some(clipboard::osc52(text));
self.toast(format!("{done}(通过终端 OSC 52)"));
}
}

/// The text of a finished mouse selection, read back from the frame.
pub fn copy_selected(&mut self, text: String) {
if text.trim().is_empty() {
return;
}
let n = text.chars().count();
self.copy_text(&text, &format!("已复制 {n} 个字符"));
}

/// The screen region a selection starting at `p` stays within.
fn selection_region(&self, p: Position) -> Rect {
let a = self.fx.areas;
if self.popup.is_some() {
return a.screen;
}
if a.input.contains(p) {
return a.input.inner(Margin {
horizontal: 1,
vertical: 1,
});
}
if a.chat.contains(p) {
// The chat text sits inside a two-column margin; the scrollbar
// is on the last column.
return a.chat.inner(Margin {
horizontal: 2,
vertical: 0,
});
}
a.screen
}

pub fn on_mouse(&mut self, m: MouseEvent) {
let p = Position::new(m.column, m.row);
match m.kind {
MouseEventKind::ScrollUp => self.scroll_by(3),
MouseEventKind::ScrollDown => self.scroll_by(-3),
MouseEventKind::ScrollUp => {
self.selection = None;
self.scroll_by(3);
}
MouseEventKind::ScrollDown => {
self.selection = None;
self.scroll_by(-3);
}
MouseEventKind::Down(MouseButton::Left) => {
self.selection = Some(Selection::new(self.selection_region(p), p));
self.selecting = true;
}
MouseEventKind::Drag(MouseButton::Left) if self.selecting => {
if let Some(sel) = &mut self.selection {
sel.extend(p);
}
}
MouseEventKind::Up(MouseButton::Left) if self.selecting => {
self.selecting = false;
if let Some(sel) = &mut self.selection {
sel.extend(p);
if sel.is_empty() {
// A plain click clears the selection.
self.selection = None;
} else {
self.copy_selection = true;
}
}
}
_ => return,
}
self.dirty = true;
Expand All @@ -1084,6 +1162,9 @@ impl App {
return;
}
self.dirty = true;
if !self.selecting {
self.selection = None;
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
let shift = key.modifiers.contains(KeyModifiers::SHIFT);
Expand Down
11 changes: 11 additions & 0 deletions src/tui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ mod game2048;
mod input;
mod markdown;
mod paste;
mod select;
mod text;
mod theme;
mod ui;
Expand Down Expand Up @@ -115,10 +116,17 @@ async fn event_loop(
// Synchronized update: terminals that support it show the frame
// all at once instead of cell by cell (others ignore it).
execute!(stdout(), BeginSynchronizedUpdate)?;
let mut copied = None;
terminal.draw(|f| {
ui::draw(f, &mut app);
let theme = app.theme;
app.fx.process(elapsed, f.buffer_mut(), &theme);
if let Some(sel) = &app.selection {
if std::mem::take(&mut app.copy_selection) {
copied = Some(select::extract(f.buffer_mut(), sel));
}
select::highlight(f.buffer_mut(), sel);
}
})?;
// The caret is drawn as a cell (ui::draw_input); the terminal
// cursor stays hidden (ratatui hides it when the frame sets no
Expand All @@ -128,6 +136,9 @@ async fn event_loop(
}
execute!(stdout(), EndSynchronizedUpdate)?;
app.dirty = false;
if let Some(text) = copied {
app.copy_selected(text);
}
}
if app.quit {
break;
Expand Down
174 changes: 174 additions & 0 deletions src/tui/select.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
//! Mouse text selection. Mouse capture (needed for wheel scrolling) stops the
//! terminal from selecting text itself, so we do it: a left-button drag marks
//! a span of screen cells inside the region where it started (the chat or the
//! prompt box), the span is drawn reversed, and on release its text is read
//! back from the rendered buffer and copied to the clipboard.

use ratatui::buffer::Buffer;
use ratatui::layout::{Position, Rect};
use ratatui::style::Modifier;
use unicode_width::UnicodeWidthStr;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Selection {
/// The region the drag started in; both ends are clamped to it.
pub region: Rect,
pub anchor: Position,
pub head: Position,
}

impl Selection {
pub fn new(region: Rect, at: Position) -> Self {
let p = clamp(region, at);
Self {
region,
anchor: p,
head: p,
}
}

pub fn extend(&mut self, to: Position) {
self.head = clamp(self.region, to);
}

pub fn is_empty(&self) -> bool {
self.anchor == self.head
}

/// Start and end in reading order (row first, then column).
fn ordered(&self) -> (Position, Position) {
let (a, b) = (self.anchor, self.head);
if (a.y, a.x) <= (b.y, b.x) {
(a, b)
} else {
(b, a)
}
}

/// Selected column range (inclusive) of each selected row.
fn rows(&self) -> impl Iterator<Item = (u16, u16, u16)> + '_ {
let (s, e) = self.ordered();
let r = self.region;
let last = r.right().saturating_sub(1);
(s.y..=e.y).map(move |y| {
let x0 = if y == s.y { s.x } else { r.x };
let x1 = if y == e.y { e.x } else { last };
(y, x0, x1)
})
}
}

fn clamp(r: Rect, p: Position) -> Position {
Position {
x: p.x.clamp(r.x, r.right().saturating_sub(1).max(r.x)),
y: p.y.clamp(r.y, r.bottom().saturating_sub(1).max(r.y)),
}
}

/// Draw the selection reversed.
pub fn highlight(buf: &mut Buffer, sel: &Selection) {
if sel.is_empty() {
return;
}
let area = buf.area;
for (y, x0, x1) in sel.rows() {
for x in x0..=x1 {
if area.contains(Position { x, y }) {
buf[(x, y)].modifier.toggle(Modifier::REVERSED);
}
}
}
}

/// The selected text, one line per row, trailing blanks trimmed.
pub fn extract(buf: &Buffer, sel: &Selection) -> String {
let area = buf.area;
let mut lines: Vec<String> = Vec::new();
for (y, x0, x1) in sel.rows() {
if y < area.top() || y >= area.bottom() {
continue;
}
let mut line = String::new();
// Walk from the row start so a wide character's hidden second cell
// (reset to a blank by ratatui) is skipped, not copied as a space.
let mut x = sel.region.x.max(area.left());
let end = x1.min(area.right().saturating_sub(1));
while x <= end {
let sym = buf[(x, y)].symbol();
let w = sym.width().max(1) as u16;
// Take a cell that starts in the range, or a wide one covering
// its first column.
if x >= x0 || x + w > x0 {
line.push_str(sym);
}
x += w;
}
lines.push(line.trim_end().to_string());
}
while lines.last().is_some_and(|l| l.is_empty()) {
lines.pop();
}
lines.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
use ratatui::style::Style;

fn buf(rows: &[&str]) -> Buffer {
let mut b = Buffer::empty(Rect::new(0, 0, 10, rows.len() as u16));
for (y, r) in rows.iter().enumerate() {
b.set_string(0, y as u16, r, Style::default());
}
b
}

#[test]
fn single_row() {
let b = buf(&["hello world"]);
let mut s = Selection::new(b.area, Position::new(0, 0));
s.extend(Position::new(4, 0));
assert_eq!(extract(&b, &s), "hello");
}

#[test]
fn backwards_multi_row() {
let b = buf(&["abc", "defgh", "ijk"]);
let mut s = Selection::new(b.area, Position::new(1, 2));
s.extend(Position::new(1, 0));
assert_eq!(extract(&b, &s), "bc\ndefgh\nij");
}

#[test]
fn wide_chars_not_padded() {
let b = buf(&["你好世界"]);
let mut s = Selection::new(b.area, Position::new(0, 0));
s.extend(Position::new(9, 0));
assert_eq!(extract(&b, &s), "你好世界");
// Starting on the hidden half still takes the whole character.
let mut s = Selection::new(b.area, Position::new(3, 0));
s.extend(Position::new(5, 0));
assert_eq!(extract(&b, &s), "好世");
}

#[test]
fn clamped_to_region() {
let b = buf(&["|abcdef|", "|ghijkl|"]);
let region = Rect::new(1, 0, 6, 2);
let mut s = Selection::new(region, Position::new(0, 0));
s.extend(Position::new(9, 1));
assert_eq!(extract(&b, &s), "abcdef\nghijkl");
}

#[test]
fn highlight_toggles_reversed() {
let mut b = buf(&["abc"]);
let mut s = Selection::new(b.area, Position::new(0, 0));
s.extend(Position::new(1, 0));
highlight(&mut b, &s);
assert!(b[(0, 0)].modifier.contains(Modifier::REVERSED));
assert!(b[(1, 0)].modifier.contains(Modifier::REVERSED));
assert!(!b[(2, 0)].modifier.contains(Modifier::REVERSED));
}
}
Loading