1818import time
1919import warnings
2020from collections .abc import Callable
21- from concurrent .futures import Future
21+ from concurrent .futures import Future , ThreadPoolExecutor
2222from datetime import datetime
2323from pathlib import Path
2424from typing import IO , Any , cast
3535from prompt_toolkit .key_binding import KeyBindings , KeyPressEvent , merge_key_bindings
3636from prompt_toolkit .key_binding .defaults import load_key_bindings
3737from prompt_toolkit .layout import ConditionalContainer , HSplit , Layout , VSplit , Window
38- from prompt_toolkit .layout .controls import BufferControl , FormattedTextControl
3938from prompt_toolkit .layout .processors import AfterInput , ConditionalProcessor
4039from prompt_toolkit .lexers import Lexer
40+ from prompt_toolkit .mouse_events import MouseButton , MouseEvent , MouseEventType
4141from prompt_toolkit .output import create_output
4242from prompt_toolkit .styles import Style
4343from rich .console import Console , RenderableType
4444from rich .text import Text
4545
4646from ..messages import MessageStore
4747from ..utils import recorded_cost , usage_tokens
48- from . import settings
48+ from . import clipboard , settings
4949from .bridge import Bridge , LedgerUI , activate , first_line , short_name
5050from .style import DIM , INK , SKY , THEME , height , width
51- from .transcript import Raw , Transcript , TranscriptControl , TranscriptWriter
51+ from .transcript import (
52+ LINE_END ,
53+ InputBelow ,
54+ Line ,
55+ Raw ,
56+ Selection ,
57+ TextBelow ,
58+ Transcript ,
59+ TranscriptControl ,
60+ TranscriptWriter ,
61+ highlight ,
62+ selected_text ,
63+ text_of ,
64+ )
5265from .view import EFFORTS , LedgerView , Picker , SessionState , model_label , run_summary
5366
5467MODES = {
88101 ("ctrl+o" , "everything from this session, unfolded" ),
89102 ("pageup pagedown" , "scroll, as does the mouse wheel · end jumps to the latest" ),
90103 ("click" , "open a file or a URL" ),
104+ ("drag" , "select text, copied when you let go" ),
91105 ("ctrl+c" , "stop the run · clear the bar · quit" ),
92106 ("ctrl+d" , "quit" ),
93107)
@@ -221,6 +235,16 @@ def __init__(self) -> None:
221235 self .worker : threading .Thread | None = None
222236 self .update_checked = False
223237 self .buf .on_text_changed += self ._reset_palette
238+ # The selection, by (line, column) in the lines last drawn: the header and the conversation.
239+ self .selection : Selection | None = None
240+ self .view_lines : list [Line ] = []
241+ self .view_start = self .view_end = 0 # the first of them on screen, and the one past the last
242+ self .view_width = 0
243+ # Off the app's loop, so a slow clipboard command never holds up the screen, and one copy at a time, so an
244+ # older selection cannot land on the clipboard after a newer one.
245+ self .copier = ThreadPoolExecutor (max_workers = 1 , thread_name_prefix = "rae-copy" )
246+ self .copies_asked = 0
247+ self .buf .on_text_changed += self ._drop_selection
224248 # Stray prints read as notices: dim and indented like the rest of the ledger.
225249 self .capture = TranscriptWriter (self ._captured , plain_style = f"fg:{ DIM } " , indent = " " )
226250
@@ -236,6 +260,9 @@ def _reset_palette(self, _buf: Buffer) -> None:
236260 if self .st .picker is not None and self .st .picker .search :
237261 self .st .picker .index = 0
238262
263+ def _drop_selection (self , _buf : Buffer ) -> None :
264+ self .selection = None
265+
239266 def _captured (self , raw : Raw ) -> None :
240267 self .view .out (raw )
241268 self .invalidate ()
@@ -421,6 +448,7 @@ def run_command(self, text: str) -> None:
421448 self .end_run ()
422449 view .flush_live ()
423450 self .transcript .clear ()
451+ self .selection = None
424452 st .scroll , st .folded , st .cost , st .tokens , st .step = 0 , False , 0.0 , 0 , 0
425453 st .last_client , st .client_name , st .host , st .run_id = None , "" , "" , None
426454 self .bridge .cost_base = 0.0
@@ -961,11 +989,84 @@ def transcript_view(self, window: Window) -> FormattedText:
961989 rows = window .render_info .window_height if window .render_info else height () - 5
962990 st .scroll = max (0 , min (st .scroll , len (lines ) - rows ))
963991 end = len (lines ) - st .scroll
992+ if self .view_width != width ():
993+ self .selection = None # the conversation wraps anew, so its lines no longer match
994+ self .view_lines , self .view_start , self .view_end , self .view_width = lines , max (0 , end - rows ), end , width ()
964995 out : list [Any ] = []
965- for i , line in enumerate (lines [max (0 , end - rows ) : end ]):
966- out += ([("" , "\n " )] if i else []) + line
996+ for i , line in enumerate (lines [self .view_start : end ]):
997+ picked = self .selection .chars (self .view_start + i ) if self .selection else None
998+ # A line with no character gives the pointer no position: the window would report the first line.
999+ shown = (highlight (line , * picked ) if picked else line ) if text_of (line ) else [("" , " " )]
1000+ out += ([("" , "\n " )] if i else []) + shown
9671001 return FormattedText (out )
9681002
1003+ def drag (self , event : MouseEvent ) -> bool :
1004+ """A drag over the conversation selects text, copied on release; a click without one still opens a link."""
1005+ at = (self .view_start + event .position .y , event .position .x )
1006+ kind , sel = event .event_type , self .selection
1007+ if kind == MouseEventType .MOUSE_DOWN :
1008+ self .selection = Selection (at , at ) if event .button == MouseButton .LEFT else None
1009+ return False
1010+ if sel is None or not sel .dragging :
1011+ return False
1012+ if kind == MouseEventType .MOUSE_MOVE and event .button == MouseButton .LEFT :
1013+ sel .head = at
1014+ return True
1015+ # A release here, or a move with no button held, after a release the session did not see.
1016+ if kind == MouseEventType .MOUSE_UP :
1017+ sel .head = at
1018+ return self .end_drag ()
1019+
1020+ def drag_below (self , event : MouseEvent ) -> bool :
1021+ """Mouse events under the conversation: a drag there reaches the end of its last line on screen."""
1022+ sel = self .selection
1023+ if sel is None or not sel .dragging or event .event_type not in (MouseEventType .MOUSE_MOVE , MouseEventType .MOUSE_UP ):
1024+ return False
1025+ sel .head = (self .view_end - 1 , LINE_END )
1026+ if event .event_type == MouseEventType .MOUSE_MOVE and event .button == MouseButton .LEFT :
1027+ return True
1028+ self .end_drag ()
1029+ return True
1030+
1031+ def end_drag (self ) -> bool :
1032+ """Copies what the drag went over; a press and release on one spot was a click."""
1033+ if self .selection is None :
1034+ return False
1035+ self .selection .dragging = False
1036+ if self .selection .anchor == self .selection .head :
1037+ self .selection = None
1038+ return False
1039+ self .copy_selection ()
1040+ return True
1041+
1042+ def copy_selection (self ) -> None :
1043+ if self .selection is None :
1044+ return
1045+ text = selected_text (self .view_lines , self .selection )
1046+ if not text .strip ():
1047+ return
1048+ rows = text .count ("\n " ) + 1
1049+ done = f"copied { rows } lines" if rows > 1 else f"copied { len (text )} characters"
1050+ self .copies_asked += 1
1051+ ticket = self .copies_asked
1052+
1053+ def copy () -> None :
1054+ if ticket != self .copies_asked :
1055+ return # a newer selection came while this one waited its turn
1056+ clipboard .copy (text , lambda data : self .call_soon (lambda : self .write_raw (data )))
1057+ self .call_soon (lambda : self .flash (done ))
1058+
1059+ self .copier .submit (copy )
1060+
1061+ def flash (self , message : str ) -> None :
1062+ self .st .flash = (message , time .time () + 2 )
1063+ self .invalidate ()
1064+
1065+ def write_raw (self , data : str ) -> None :
1066+ if self .app is not None :
1067+ self .app .output .write_raw (data )
1068+ self .app .output .flush ()
1069+
9691070 def build (self ) -> Application :
9701071 st , view , buf = self .st , self .view , self .buf
9711072 palette_open = Condition (self .palette_active )
@@ -989,11 +1090,11 @@ def picker_view() -> FormattedText:
9891090 return view .menu (rows , title = p .title , empty = "nothing matches what you typed" )
9901091
9911092 transcript_window : Window = Window (wrap_lines = False )
992- transcript_window .content = TranscriptControl (lambda : self .transcript_view (transcript_window ), self .scroll )
1093+ transcript_window .content = TranscriptControl (lambda : self .transcript_view (transcript_window ), self .scroll , self . drag )
9931094 kb = self .bindings (palette_open , picker_open )
9941095
9951096 def text_window (fn : Callable [[], Any ]) -> Window :
996- return Window (FormattedTextControl (fn ), dont_extend_height = True )
1097+ return Window (TextBelow (fn , self . drag_below ), dont_extend_height = True )
9971098
9981099 picker_hinted = Condition (lambda : bool (st .picker and st .picker .hint ))
9991100 placeholder = ConditionalProcessor (
@@ -1016,9 +1117,11 @@ def text_window(fn: Callable[[], Any]) -> Window:
10161117 text_window (lambda : FormattedText (view .seam ())),
10171118 VSplit (
10181119 [
1019- Window (FormattedTextControl (lambda : FormattedText (view .marker ())), dont_extend_width = True , dont_extend_height = True ),
1120+ Window (TextBelow (lambda : FormattedText (view .marker ()), self . drag_below ), dont_extend_width = True , dont_extend_height = True ),
10201121 Window (
1021- BufferControl (buffer = buf , lexer = InputLexer (st ), input_processors = [placeholder , follow_hint , picker_hint ]),
1122+ InputBelow (
1123+ self .drag_below , buffer = buf , lexer = InputLexer (st ), input_processors = [placeholder , follow_hint , picker_hint ]
1124+ ),
10221125 dont_extend_height = True ,
10231126 wrap_lines = True ,
10241127 ),
0 commit comments