use std::{
future::Future,
io,
pin::Pin,
sync::Arc,
task::{Context as TaskContext, Poll},
};
use gpui_kit::{Context, SharedString, Task};
use rust_i18n::t;
use super::{
ColumnOf, LiveGridDelegate, LiveGridState, columns::column_of, pending::PendingValues,
selection::ScopedSelection,
};
use crate::{
engine::{DisplayRow, Projection},
export::{
CellExport, ExportColumn, ExportControl, ExportError, ExportFormat, ExportLine, ExportRow,
ExportScope, ExportTable,
},
model::{ColumnId, ColumnIx, ColumnSet, GridColumns as _, GridRow, NumberFormat},
state::{ColumnAlign, ColumnZone},
store::{PinnedEdge, StoreSnapshot},
};
pub struct ExportRequest<R: GridRow> {
scope: ExportScope,
header: ExportHeader,
empty: EmptyExport,
columns: Option<Vec<R::Column>>,
cells: Option<CellExport<R>>,
}
impl<R: GridRow> ExportRequest<R> {
pub fn new(scope: ExportScope) -> Self {
Self {
scope,
header: ExportHeader::default(),
empty: EmptyExport::default(),
columns: None,
cells: None,
}
}
pub fn with_header(self, header: ExportHeader) -> Self {
Self { header, ..self }
}
pub fn with_empty(self, empty: EmptyExport) -> Self {
Self { empty, ..self }
}
pub fn with_columns(self, columns: impl IntoIterator<Item = R::Column>) -> Self {
Self {
columns: Some(columns.into_iter().collect()),
..self
}
}
pub fn with_cell_export(self, cells: CellExport<R>) -> Self {
Self {
cells: Some(cells),
..self
}
}
pub fn scope(&self) -> ExportScope {
self.scope
}
pub fn header(&self) -> ExportHeader {
self.header
}
pub fn empty(&self) -> EmptyExport {
self.empty
}
}
impl<R: GridRow> Default for ExportRequest<R> {
fn default() -> Self {
Self::new(ExportScope::Visible)
}
}
impl<R: GridRow> Clone for ExportRequest<R> {
fn clone(&self) -> Self {
Self {
scope: self.scope,
header: self.header,
empty: self.empty,
columns: self.columns.clone(),
cells: self.cells.clone(),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExportHeader {
None,
#[default]
Titles,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum EmptyExport {
#[default]
Nothing,
HeaderOnly,
}
#[must_use = "dropping an export job cancels the export"]
pub struct ExportJob<T> {
control: ExportControl,
task: Option<Task<()>>,
done: Box<async_channel::Receiver<Result<ExportOutcome<T>, ExportError>>>,
result: Pin<Box<dyn Future<Output = Result<ExportOutcome<T>, ExportError>> + Send>>,
detached: bool,
}
impl<T: Send + 'static> ExportJob<T> {
fn new(
control: ExportControl,
task: Task<()>,
done: async_channel::Receiver<Result<ExportOutcome<T>, ExportError>>,
) -> Self {
let result = {
let done = done.clone();
Box::pin(async move {
done.recv().await.unwrap_or(Err(ExportError::Cancelled))
})
};
Self {
control,
task: Some(task),
done: Box::new(done),
result,
detached: false,
}
}
}
impl<T> ExportJob<T> {
pub fn progress(&self) -> ExportProgress {
ExportProgress {
rows_written: self.control.rows_written(),
rows_total: self.control.rows_total(),
}
}
pub fn cancel(&self) {
self.control.cancel();
}
pub fn is_finished(&self) -> bool {
self.done.is_closed()
}
pub fn detach(mut self) {
if let Some(task) = self.task.take() {
task.detach();
}
self.detached = true;
}
}
impl<T> Future for ExportJob<T> {
type Output = Result<ExportOutcome<T>, ExportError>;
fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let result = std::task::ready!(this.result.as_mut().poll(cx));
this.task = None;
Poll::Ready(result)
}
}
impl<T> Drop for ExportJob<T> {
fn drop(&mut self) {
if !self.detached {
self.control.cancel();
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ExportProgress {
rows_written: usize,
rows_total: usize,
}
impl ExportProgress {
pub fn rows_written(&self) -> usize {
self.rows_written
}
pub fn rows_total(&self) -> usize {
self.rows_total
}
pub fn fraction(&self) -> f32 {
if self.rows_total == 0 {
return 1.0;
}
(self.rows_written.min(self.rows_total) as f64 / self.rows_total as f64) as f32
}
}
#[derive(Clone, Debug)]
pub struct ExportOutcome<T> {
output: T,
rows: usize,
data_rows: usize,
bytes: Option<u64>,
}
impl<T> ExportOutcome<T> {
pub fn output(&self) -> &T {
&self.output
}
pub fn into_output(self) -> T {
self.output
}
pub fn rows(&self) -> usize {
self.rows
}
pub fn data_rows(&self) -> usize {
self.data_rows
}
pub fn bytes(&self) -> Option<u64> {
self.bytes
}
}
enum CaptureRows<K> {
Lines(Arc<Projection>),
Expanded(Arc<Projection>),
Scoped(ScopedSelection<K>),
}
impl<K> CaptureRows<K> {
fn len(&self) -> usize {
match self {
Self::Lines(projection) => projection.len(),
Self::Expanded(projection) => projection
.rows()
.len()
.saturating_add(projection.groups().len().saturating_mul(2)),
Self::Scoped(scoped) => scoped.len(),
}
}
}
struct CapturedColumn<C> {
column: C,
title: SharedString,
width: f32,
align: ColumnAlign,
zone: ColumnZone,
bands: Box<[SharedString]>,
}
fn pinned_count<R: GridRow>(snapshot: &StoreSnapshot<R>) -> usize {
snapshot.pinned_rows(PinnedEdge::Top).len() + snapshot.pinned_rows(PinnedEdge::Bottom).len()
}
pub(super) struct ExportCapture<R: GridRow> {
snapshot: Arc<StoreSnapshot<R>>,
rows: CaptureRows<R::Key>,
columns: Vec<CapturedColumn<R::Column>>,
header: bool,
value_columns: Vec<(ColumnId, R::Column)>,
totals: Option<(PinnedEdge, SharedString)>,
pending: Arc<PendingValues<R::Key, R::Column>>,
formats: Arc<[NumberFormat]>,
cells: CellExport<R>,
is_empty: bool,
}
impl<R: GridRow> ExportCapture<R> {
pub(super) fn is_empty(&self) -> bool {
self.is_empty
}
pub(super) fn row_estimate(&self) -> usize {
let bands = match self.rows {
CaptureRows::Lines(_) | CaptureRows::Expanded(_) => {
pinned_count(&self.snapshot) + usize::from(self.totals.is_some())
}
CaptureRows::Scoped(_) => 0,
};
self.rows.len().saturating_add(bands)
}
pub(super) fn cell_count(&self) -> usize {
self.row_estimate().saturating_mul(self.columns.len())
}
pub(super) fn write<T>(
&self,
write: impl FnOnce(&ExportTable<'_, R>, &CellExport<R>) -> T,
) -> T {
let band_titles: Vec<&str> = self
.columns
.iter()
.flat_map(|column| column.bands.iter().map(SharedString::as_ref))
.collect();
let mut band_start = 0;
let columns: Vec<ExportColumn<'_, R::Column>> = self
.columns
.iter()
.map(|column| {
let bands = &band_titles[band_start..band_start + column.bands.len()];
band_start += column.bands.len();
ExportColumn::new(column.column, &column.title)
.with_width(column.width)
.with_align(column.align)
.with_zone(column.zone)
.with_bands(bands)
})
.collect();
let mut rows = self.rows();
for row in &mut rows {
*row = row.with_number_formats(&self.formats);
}
write(
&ExportTable::new(&columns, &rows).with_header(self.header),
&self.cells,
)
}
fn rows(&self) -> Vec<ExportRow<'_, R>> {
let exported = self
.columns
.iter()
.fold(ColumnSet::EMPTY, |mut set, column| {
set.insert(column.column.ix());
set
});
match &self.rows {
CaptureRows::Lines(projection) => self.view_rows(
projection,
(0..projection.len()).map_while(|ix| projection.line(ix)),
false,
),
CaptureRows::Expanded(projection) => {
self.view_rows(projection, projection.expanded_lines(), true)
}
CaptureRows::Scoped(scoped) => scoped
.keys()
.iter()
.enumerate()
.filter_map(|(ix, key)| {
let selected = scoped.columns(ix);
if !selected.intersects(exported) {
return None;
}
let row = self.snapshot.get(key)?;
Some(self.data_row(row).with_columns(selected))
})
.collect(),
}
}
fn data_row<'a>(&'a self, row: &'a R) -> ExportRow<'a, R> {
let export = ExportRow::new(row);
if self.pending.is_empty() {
return export;
}
match self.pending.get(row.key()) {
Some(values) => export.with_pending(values),
None => export,
}
}
fn view_rows<'a>(
&'a self,
projection: &'a Projection,
lines: impl Iterator<Item = DisplayRow> + 'a,
mark_hidden: bool,
) -> Vec<ExportRow<'a, R>> {
let snapshot = &*self.snapshot;
let groups = projection.groups();
let is_tree = projection.is_tree();
let first_column = self.columns[0].column;
let totals = |edge| {
self.totals
.as_ref()
.filter(|(at, _)| *at == edge)
.map(|(_, label)| {
ExportRow::totals(projection.totals(), Some((first_column, label.as_ref())))
.with_band(edge)
})
};
let pinned = |edge| {
snapshot
.pinned_rows(edge)
.iter()
.map(move |row| ExportRow::new(&**row).with_band(edge))
};
let mut hidden = HiddenLines::default();
let mut rows = Vec::with_capacity(self.rows.len() + pinned_count(snapshot) + 1);
rows.extend(totals(PinnedEdge::Top));
rows.extend(pinned(PinnedEdge::Top));
rows.extend(lines.filter_map(|line| {
let (row, is_hidden) = match line {
DisplayRow::Data { row: id, depth } => {
let branch = if is_tree { projection.branch(id) } else { None };
let collapsed = branch.is_some_and(|branch| !branch.is_expanded());
let is_hidden = mark_hidden && hidden.next(depth, collapsed, false);
let row = self.data_row(snapshot.row(id)?).with_depth(depth);
(
match branch {
Some(branch) => row.with_branch(branch),
None => row,
},
is_hidden,
)
}
DisplayRow::GroupCaption { group, depth } => {
let group = groups.get(group)?;
let is_hidden = mark_hidden && hidden.next(depth, !group.is_expanded(), false);
let level = group.level_id();
let value_column = self
.value_columns
.iter()
.find(|(id, _)| id == level)
.map_or(first_column, |(_, column)| *column);
(ExportRow::caption(value_column, group), is_hidden)
}
DisplayRow::GroupFooter { group, depth } => {
let group = groups.get(group)?;
let is_hidden = mark_hidden && hidden.next(depth, false, !group.is_expanded());
(ExportRow::footer(group), is_hidden)
}
};
Some(row.with_hidden(is_hidden))
}));
rows.extend(pinned(PinnedEdge::Bottom));
rows.extend(totals(PinnedEdge::Bottom));
rows
}
fn run<T>(
&self,
empty: EmptyExport,
control: &ExportControl,
write: impl FnOnce(
&ExportTable<'_, R>,
&CellExport<R>,
&ExportControl,
) -> Result<(T, Option<u64>), ExportError>,
) -> Result<ExportOutcome<T>, ExportError> {
control.advance(0)?;
self.write(|table, cells| {
let rows = table.rows().len();
control.set_rows_total(rows);
if rows == 0 && empty == EmptyExport::Nothing {
return Err(ExportError::Nothing);
}
let (output, bytes) = write(table, cells, control)?;
Ok(ExportOutcome {
output,
rows,
data_rows: table
.rows()
.iter()
.filter(|row| row.line() == ExportLine::Data)
.count(),
bytes,
})
})
}
}
#[derive(Default)]
struct HiddenLines {
below: Option<u16>,
}
impl HiddenLines {
fn next(&mut self, depth: u16, collapsed: bool, collapsed_footer: bool) -> bool {
let under_collapsed = match self.below {
Some(below) if depth > below => true,
_ => {
self.below = None;
false
}
};
if !under_collapsed && collapsed {
self.below = Some(depth);
}
under_collapsed || collapsed_footer
}
}
struct CountingWriter<W> {
inner: W,
bytes: u64,
}
impl<W: io::Write> io::Write for CountingWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let written = self.inner.write(buf)?;
self.bytes += written as u64;
Ok(written)
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.inner.write_all(buf)?;
self.bytes += buf.len() as u64;
Ok(())
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
#[cfg(not(target_family = "wasm"))]
fn write_through_part_file(
path: &std::path::Path,
control: &ExportControl,
write: impl FnOnce(&mut dyn io::Write) -> Result<(), ExportError>,
) -> Result<u64, ExportError> {
let Some(name) = path.file_name() else {
return Err(
io::Error::new(io::ErrorKind::InvalidInput, "the export path names no file").into(),
);
};
let mut part_name = name.to_os_string();
part_name.push(".part");
let part = path.with_file_name(part_name);
let written = (|| {
let file = std::fs::File::create(&part)?;
let mut out = CountingWriter {
inner: io::BufWriter::new(file),
bytes: 0,
};
write(&mut out)?;
let bytes = out.bytes;
let file = out
.inner
.into_inner()
.map_err(io::IntoInnerError::into_error)?;
file.sync_all()?;
drop(file);
control.advance(0)?;
std::fs::rename(&part, path)?;
Ok(bytes)
})();
if written.is_err() {
let _ = std::fs::remove_file(&part);
}
written
}
impl<D: LiveGridDelegate> LiveGridState<D> {
pub fn export<W: io::Write + Send + 'static>(
&mut self,
request: ExportRequest<D::Row>,
format: impl ExportFormat<D::Row>,
sink: W,
cx: &mut Context<Self>,
) -> Result<ExportJob<W>, ExportError> {
self.start_export(
request,
move |table, cells, control| {
let mut out = CountingWriter {
inner: sink,
bytes: 0,
};
format.export(table, cells, &mut out, control)?;
Ok((out.inner, Some(out.bytes)))
},
cx,
)
}
#[cfg(not(target_family = "wasm"))]
pub fn export_to_path(
&mut self,
request: ExportRequest<D::Row>,
format: impl ExportFormat<D::Row>,
path: impl Into<std::path::PathBuf>,
cx: &mut Context<Self>,
) -> Result<ExportJob<std::path::PathBuf>, ExportError> {
let path = path.into();
self.start_export(
request,
move |table, cells, control| {
let bytes = write_through_part_file(&path, control, |out| {
format.export(table, cells, out, control)
})?;
Ok((path, Some(bytes)))
},
cx,
)
}
pub fn export_with<T: Send + 'static>(
&mut self,
request: ExportRequest<D::Row>,
write: impl FnOnce(
&ExportTable<'_, D::Row>,
&CellExport<D::Row>,
&ExportControl,
) -> Result<T, ExportError>
+ Send
+ 'static,
cx: &mut Context<Self>,
) -> Result<ExportJob<T>, ExportError> {
self.start_export(
request,
move |table, cells, control| Ok((write(table, cells, control)?, None)),
cx,
)
}
pub fn is_export_empty(&self, scope: ExportScope) -> bool {
self.capture(scope, None, true, CellExport::default())
.is_empty()
}
fn start_export<T: Send + 'static>(
&mut self,
request: ExportRequest<D::Row>,
write: impl FnOnce(
&ExportTable<'_, D::Row>,
&CellExport<D::Row>,
&ExportControl,
) -> Result<(T, Option<u64>), ExportError>
+ Send
+ 'static,
cx: &mut Context<Self>,
) -> Result<ExportJob<T>, ExportError> {
let ExportRequest {
scope,
header,
empty,
columns,
cells,
} = request;
let cells = cells.unwrap_or_else(|| self.copy_cells().clone());
let capture = self.capture(
scope,
columns.as_deref(),
header == ExportHeader::Titles,
cells,
);
if capture.is_empty() && (empty == EmptyExport::Nothing || capture.columns.is_empty()) {
return Err(ExportError::Nothing);
}
let control = ExportControl::new(capture.row_estimate());
let (done, result) = async_channel::bounded(1);
let job_control = control.clone();
let task = self.runner.run(
Box::new(move || {
let _ = done.try_send(capture.run(empty, &job_control, write));
}),
cx,
);
Ok(ExportJob::new(control, task, result))
}
pub(super) fn capture(
&self,
scope: ExportScope,
columns: Option<&[ColumnOf<D>]>,
header: bool,
cells: CellExport<D::Row>,
) -> ExportCapture<D::Row> {
let (rows, selected) = match scope {
ExportScope::Selection => {
let scoped = self.command_scope(self.focus_target().as_ref());
let selected = (0..scoped.len()).fold(ColumnSet::EMPTY, |mut set, ix| {
set.union_with(scoped.columns(ix));
set
});
(CaptureRows::Scoped(scoped), selected)
}
ExportScope::Visible => (
CaptureRows::Lines(self.projection.clone()),
self.columns.visible_set(),
),
ExportScope::Expanded => (
CaptureRows::Expanded(self.projection.clone()),
self.columns.visible_set(),
),
};
let columns: Vec<CapturedColumn<ColumnOf<D>>> = match columns {
Some(columns) => columns
.iter()
.filter_map(|column| self.captured_column(column.ix()))
.collect(),
None => {
let selected = if selected.is_empty() {
self.columns.visible_set()
} else {
selected
};
self.columns
.visible()
.filter(|ix| selected.contains(*ix))
.filter_map(|ix| self.captured_column(ix))
.collect()
}
};
let (value_columns, totals) = match rows {
CaptureRows::Scoped(_) => (Vec::new(), None),
CaptureRows::Lines(_) | CaptureRows::Expanded(_) => {
let value_columns = self
.view
.group_by()
.iter()
.filter_map(|level| {
let column = level.as_column()?;
let exported = columns.iter().any(|each| each.column == column);
exported.then(|| (level.id(), column))
})
.collect();
let totals = self
.totals()
.filter(|_| !self.projection.totals().is_empty())
.map(|edge| {
let label = SharedString::from(t!("live_grid.totals.label").into_owned());
(edge, label)
});
(value_columns, totals)
}
};
let no_rows = match &rows {
CaptureRows::Scoped(scoped) => scoped.is_empty(),
CaptureRows::Lines(projection) | CaptureRows::Expanded(projection) => {
projection.is_empty() && pinned_count(&self.snapshot) == 0 && totals.is_none()
}
};
ExportCapture {
snapshot: self.snapshot.clone(),
rows,
is_empty: no_rows || columns.is_empty(),
columns,
header,
value_columns,
totals,
pending: self.pending_values(),
formats: self.columns.number_formats(),
cells,
}
}
fn captured_column(&self, ix: ColumnIx) -> Option<CapturedColumn<ColumnOf<D>>> {
let column = self.columns.get(ix)?;
Some(CapturedColumn {
column: column_of(ix),
title: column.title().clone(),
width: f32::from(self.columns.width(ix)),
align: column.align(),
zone: self.columns.zone_of(ix),
bands: self
.columns
.bands_of(ix)
.iter()
.map(|band| {
self.columns
.band_title(band)
.cloned()
.unwrap_or_else(|| SharedString::new_static(band))
})
.collect(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hidden_lines() {
let mut hidden = HiddenLines::default();
let walk = [
(0, true, false, false),
(1, false, false, true),
(2, false, false, true),
(1, true, false, true),
(2, false, false, true),
(1, false, true, true),
(0, false, true, true),
(0, false, false, false),
(1, true, false, false),
(2, false, false, true),
(1, false, true, true),
(1, false, false, false),
(2, false, false, false),
(1, false, false, false),
(0, false, false, false),
];
for (ix, (depth, collapsed, collapsed_footer, expected)) in walk.into_iter().enumerate() {
assert_eq!(
hidden.next(depth, collapsed, collapsed_footer),
expected,
"line {ix}"
);
}
}
#[test]
fn test_progress_fraction() {
let progress = |rows_written, rows_total| ExportProgress {
rows_written,
rows_total,
};
assert_eq!(progress(0, 300).fraction(), 0.0);
assert_eq!(progress(150, 300).fraction(), 0.5);
assert_eq!(progress(300, 300).fraction(), 1.0);
assert_eq!(progress(400, 300).fraction(), 1.0);
assert_eq!(progress(0, 0).fraction(), 1.0);
}
}