use std::sync::Arc;
use gpui_kit::{ClipboardItem, Context, Task, Window};
use super::{LiveGridDelegate, LiveGridState, export::ExportCapture};
use crate::{
actions,
export::{CellExport, ExportScope, Exporter, TsvExporter},
model::GridRow,
};
#[cfg(doc)]
use crate::export::RawCells;
const INLINE_COPY_CELLS: usize = 40_000;
pub(super) struct CopySlot<R: GridRow> {
exporter: Arc<dyn Exporter<R>>,
cells: CellExport<R>,
job: Option<Task<()>>,
}
impl<R: GridRow> Default for CopySlot<R> {
fn default() -> Self {
Self {
exporter: Arc::new(TsvExporter),
cells: CellExport::default(),
job: None,
}
}
}
impl<D: LiveGridDelegate> LiveGridState<D> {
pub fn with_cell_export(mut self, export: CellExport<D::Row>) -> Self {
self.copy.cells = export;
self
}
pub fn with_exporter(mut self, exporter: impl Exporter<D::Row>) -> Self {
self.copy.exporter = Arc::new(exporter);
self
}
pub fn copy(&mut self, cx: &mut Context<Self>) -> bool {
self.copy_scope(ExportScope::Selection, cx)
}
pub fn copy_all(&mut self, cx: &mut Context<Self>) -> bool {
self.copy_scope(ExportScope::Visible, cx)
}
pub fn copy_scope(&mut self, scope: ExportScope, cx: &mut Context<Self>) -> bool {
let header = scope != ExportScope::Selection;
let capture = self.capture(scope, None, header, self.copy.cells.clone());
if capture.is_empty() {
return false;
}
self.start_copy(capture, cx)
}
pub(super) fn on_copy(&mut self, _: &actions::Copy, _: &mut Window, cx: &mut Context<Self>) {
if !self.copy(cx) {
cx.propagate();
}
}
pub(super) fn on_copy_all(
&mut self,
_: &actions::CopyAll,
_: &mut Window,
cx: &mut Context<Self>,
) {
if !self.copy_all(cx) {
cx.propagate();
}
}
pub(super) fn copy_cells(&self) -> &CellExport<D::Row> {
&self.copy.cells
}
fn start_copy(&mut self, capture: ExportCapture<D::Row>, cx: &mut Context<Self>) -> bool {
self.copy.job = None;
let exporter = self.copy.exporter.clone();
let write = move |capture: &ExportCapture<D::Row>| {
capture.write(|table, cells| {
if table.rows().is_empty() {
return None;
}
let mut text = String::new();
exporter.export(table, cells, &mut text);
Some(text)
})
};
if capture.cell_count() <= INLINE_COPY_CELLS {
let Some(text) = write(&capture) else {
return false;
};
cx.write_to_clipboard(ClipboardItem::new_string(text));
return true;
}
let (done, result) = async_channel::bounded(1);
let job = self.runner.run(
Box::new(move || {
let _ = done.try_send(write(&capture));
}),
cx,
);
self.copy.job = Some(cx.spawn(async move |this, cx| {
job.await;
let Ok(text) = result.recv().await else {
return;
};
let _ = this.update(cx, |state, cx| {
state.copy.job = None;
if let Some(text) = text {
cx.write_to_clipboard(ClipboardItem::new_string(text));
}
});
}));
true
}
}