//! Open a link only for an unmodified press and release on the same cell with no selection. Leave modified clicks to //! the terminal. use crate::prelude::*; /// Registers the link click handler. `app::mount` calls it once. pub fn install(tui: &Rc) { let pressed = Rc::new(Cell::new(None::<(u16, u16)>)); tui.app.on_mouse(bind!(tui, |tui, _, event| { let plain = [Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT] .into_iter() .all(|modifier| !event.modifiers.contains(modifier)); match event.kind { // The root's shape reaches every widget without one of its own, such as transcript text. MouseEventKind::Moved => { tui.app.root().mouse_pointer(opencode_ui::click_pointer(link_at(&tui.app, event.x, event.y).is_some())); } MouseEventKind::Down(MouseButton::Left) => { pressed.set(plain.then_some((event.x, event.y))); } MouseEventKind::Drag(_) => pressed.set(None), MouseEventKind::Up(MouseButton::Left) => { let click = pressed.take() == Some((event.x, event.y)) && plain; if !click || tui.app.selected_text().is_some() { return; } if let Some(url) = link_at(&tui.app, event.x, event.y) && let Err(error) = open_url(&url) { tui.toasts.error(error); } } _ => {} } })); } /// `Link`'s `onMouseUp`: a plain left release on `text` opens `url`, and a failure is ignored. A dialog needs it: its /// panel stops a release before [`install`]'s handler sees it. pub fn open_on_click(app: &App, text: &Text, url: String) { on_click(app, text, move || drop(open_url(&url))); } /// `Link`'s `onMouseUp` with its own action: a plain left release on `text` with no selection runs `open`. pub fn on_click(app: &App, text: &Text, open: impl Fn() + 'static) { let app = app.clone(); text.mouse_pointer(MousePointer::POINTER).on_mouse(move |_, event| { let plain = [Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT] .into_iter() .all(|modifier| !event.modifiers.contains(modifier)); if event.kind == MouseEventKind::Up(MouseButton::Left) && plain && app.selected_text().is_none() { open(); } }); } pub fn link_at(app: &App, x: u16, y: u16) -> Option { let session = app.session(); let id = session.link_id(i32::from(x), i32::from(y)).ok()??; session.context().link_url(id).ok() } /// `openUrl`: http and https links only, in the system browser. pub fn open_url(input: &str) -> Result<(), String> { open(&opencode_ui::open::web_url(input)?) } pub fn open_path(path: &str) -> Result<(), String> { open(path) } fn open(target: &str) -> Result<(), String> { if testing::record(target) { return Ok(()); } spawn(opencode_ui::open::command(target)).map(drop) } /// Starts `command` and waits for it off the UI thread, so the exited opener does not stay a zombie. fn spawn(mut command: std::process::Command) -> Result { let mut child = command .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .spawn() .map_err(|error| error.to_string())?; let id = child.id(); std::thread::spawn(move || child.wait()); Ok(id) } /// A sink for tests: while a [`Capture`] lives on the UI thread, opens and copies are recorded instead of /// reaching the system, and clipboard reads take the queued `clipboard` outcomes (`Empty` once none are left). #[doc(hidden)] pub mod testing { use super::*; thread_local! { static SINK: RefCell>> = const { RefCell::new(None) }; } #[derive(Default)] pub struct Sink { pub opened: RefCell>, pub copied: RefCell>, pub clipboard: RefCell>, } /// Records until dropped. pub struct Capture(pub Rc); impl Drop for Capture { fn drop(&mut self) { SINK.with(|sink| sink.borrow_mut().take()); } } pub fn capture() -> Capture { let sink = Rc::new(Sink::default()); SINK.with(|slot| *slot.borrow_mut() = Some(sink.clone())); Capture(sink) } pub(crate) fn record(target: &str) -> bool { sink().is_some_and(|sink| { sink.opened.borrow_mut().push(target.to_owned()); true }) } pub(crate) fn sink() -> Option> { SINK.with(|sink| sink.borrow().clone()) } } #[cfg(test)] mod tests { use super::*; #[test] fn only_web_links_open_in_the_browser() { let capture = testing::capture(); assert_eq!(open_url("https://opencode.ai/v2/docs"), Ok(())); assert_eq!( open_url("file:///etc/passwd"), Err("Only http and https links can be opened in the browser: file:///etc/passwd".into()) ); assert!(open_url("not a url").is_err()); for url in ["https://bücher.example", "https://Bücher.example", "https://%42%C3%BCcher.example"] { assert_eq!( open_url(url), Err(format!( "{url}: a host name must be ASCII; write an international name in its punycode (xn--) form" )) ); } assert_eq!(open_path("/tmp/project"), Ok(())); assert_eq!(*capture.0.opened.borrow(), ["https://opencode.ai/v2/docs", "/tmp/project"]); } #[cfg(target_os = "linux")] #[test] fn an_exited_opener_is_reaped() { let id = spawn(std::process::Command::new("true")).unwrap(); let reaped = (0..500).any(|_| { std::thread::sleep(std::time::Duration::from_millis(10)); std::fs::metadata(format!("/proc/{id}")).is_err() }); assert!(reaped, "the opener {id} was never reaped"); } }