text-document-io 1.5.6

Import/export for text-document: plain text, Markdown, HTML, LaTeX, DOCX
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Generated by Qleany v1.4.8 from feature_use_case.tera
use crate::ExportDocxDto;
use crate::ExportDocxResultDto;
use anyhow::{Result, anyhow};
use common::database::QueryUnitOfWork;
use common::database::rope_helpers::block_content_via_store;
use common::entities::{Block, Document, Frame, List, Root, Table, TableCell};
use common::format_runs::InlineContent;
use common::long_operation::LongOperation;
use common::types::{EntityId, ROOT_ENTITY_ID};
use std::collections::HashSet;
use std::sync::Arc;

pub trait ExportDocxUnitOfWorkFactoryTrait: Send + Sync {
    fn create(&self) -> Box<dyn ExportDocxUnitOfWorkTrait>;
}

#[macros::uow_action(entity = "Root", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Root", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "Document", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Document", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "Frame", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Frame", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "Block", action = "GetMultiRO", thread_safe = true)]
#[macros::uow_action(entity = "Block", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "List", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Table", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Table", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "TableCell", action = "GetMultiRO", thread_safe = true)]
pub trait ExportDocxUnitOfWorkTrait: QueryUnitOfWork + Send + Sync {}

pub struct ExportDocxUseCase {
    uow_factory: Box<dyn ExportDocxUnitOfWorkFactoryTrait>,
    dto: ExportDocxDto,
}

impl ExportDocxUseCase {
    pub fn new(
        uow_factory: Box<dyn ExportDocxUnitOfWorkFactoryTrait>,
        dto: &ExportDocxDto,
    ) -> Self {
        ExportDocxUseCase {
            uow_factory,
            dto: dto.clone(),
        }
    }
}

impl LongOperation for ExportDocxUseCase {
    type Output = ExportDocxResultDto;

    fn execute(
        &self,
        progress_callback: Box<dyn Fn(common::long_operation::OperationProgress) + Send>,
        cancel_flag: Arc<std::sync::atomic::AtomicBool>,
    ) -> Result<Self::Output> {
        use docx_rs::*;
        use std::sync::atomic::Ordering;

        // Validate output path
        let output_path = std::path::Path::new(&self.dto.output_path);
        if let Some(parent) = output_path.parent()
            && !parent.as_os_str().is_empty()
            && !parent.exists()
        {
            return Err(anyhow!(
                "Output directory does not exist: '{}'",
                parent.display()
            ));
        }

        progress_callback(common::long_operation::OperationProgress::new(
            0.0,
            Some("Starting DOCX export...".to_string()),
        ));

        let uow = self.uow_factory.create();
        uow.begin_transaction()?;

        // Step 1: Get Root and Document
        let root = uow
            .get_root(&ROOT_ENTITY_ID)?
            .ok_or_else(|| anyhow!("Root entity not found"))?;

        let doc_ids = uow.get_root_relationship(
            &root.id,
            &common::direct_access::root::RootRelationshipField::Document,
        )?;
        let doc_id = *doc_ids
            .first()
            .ok_or_else(|| anyhow!("Root has no associated Document"))?;

        let frame_ids = uow.get_document_relationship(
            &doc_id,
            &common::direct_access::document::DocumentRelationshipField::Frames,
        )?;

        // Collect all cell frame IDs so we can skip them in the main loop
        let table_ids = uow.get_document_relationship(
            &doc_id,
            &common::direct_access::document::DocumentRelationshipField::Tables,
        )?;
        let mut cell_frame_ids: HashSet<EntityId> = HashSet::new();
        for tid in &table_ids {
            let cell_ids = uow.get_table_relationship(
                tid,
                &common::direct_access::table::TableRelationshipField::Cells,
            )?;
            let cells_opt = uow.get_table_cell_multi(&cell_ids)?;
            for cell in cells_opt.into_iter().flatten() {
                if let Some(cf_id) = cell.cell_frame {
                    cell_frame_ids.insert(cf_id);
                }
            }
        }

        let mut docx = Docx::new();
        let mut paragraph_count: i64 = 0;

        progress_callback(common::long_operation::OperationProgress::new(
            10.0,
            Some("Walking document tree...".to_string()),
        ));

        for frame_id in &frame_ids {
            if cancel_flag.load(Ordering::Relaxed) {
                uow.end_transaction()?;
                return Err(anyhow!("Operation was cancelled"));
            }

            // Skip cell frames — they're rendered as part of their table
            if cell_frame_ids.contains(frame_id) {
                continue;
            }

            // Check if this is a table anchor frame
            let frame = uow.get_frame(frame_id)?;
            if let Some(ref f) = frame
                && let Some(table_id) = f.table
            {
                let table = self.render_table_docx(&*uow, &table_id)?;
                docx = docx.add_table(table);
                paragraph_count += 1;
                continue;
            }

            let block_ids = uow.get_frame_relationship(
                frame_id,
                &common::direct_access::frame::FrameRelationshipField::Blocks,
            )?;

            if block_ids.is_empty() {
                continue;
            }

            let blocks_opt = uow.get_block_multi(&block_ids)?;
            let mut blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();
            blocks.sort_by_key(|b| b.document_position);
            let total = blocks.len();

            for (idx, block) in blocks.iter().enumerate() {
                if cancel_flag.load(Ordering::Relaxed) {
                    uow.end_transaction()?;
                    return Err(anyhow!("Operation was cancelled"));
                }

                let block_text = block_content_via_store(block, &uow.store());
                let elements = common::format_runs_query::inline_segments_for_block(
                    &uow.store(),
                    block.id,
                    &block_text,
                );

                let mut paragraph = Paragraph::new();

                // Apply heading style
                if let Some(level) = block.fmt_heading_level {
                    let style_name = format!("Heading{}", level.clamp(1, 6));
                    paragraph = paragraph.style(&style_name);
                }
                // Apply line height (thousandths → 240ths: 1000 = 240, 1500 = 360)
                if let Some(lh) = block.fmt_line_height {
                    let twips = (lh as f64 / 1000.0 * 240.0) as i32;
                    paragraph = paragraph.line_spacing(
                        LineSpacing::new()
                            .line_rule(LineSpacingType::Auto)
                            .line(twips),
                    );
                }
                // Apply non-breakable lines
                if block.fmt_non_breakable_lines == Some(true) {
                    paragraph = paragraph.keep_lines(true);
                }
                // Note: bidi (RTL direction) and paragraph shading (background_color)
                // are not directly exposed on Paragraph in docx-rs 0.4.

                for elem in &elements {
                    let text = match &elem.content {
                        InlineContent::Text(t) => t.clone(),
                        InlineContent::Image { name, .. } => {
                            format!("[Image: {}]", name)
                        }
                        InlineContent::Empty => String::new(),
                    };

                    if text.is_empty() {
                        continue;
                    }

                    let mut run = Run::new().add_text(text);

                    if elem.fmt_font_bold == Some(true) {
                        run = run.bold();
                    }
                    if elem.fmt_font_italic == Some(true) {
                        run = run.italic();
                    }
                    if elem.fmt_font_underline == Some(true) {
                        run = run.underline("single");
                    }
                    if elem.fmt_font_strikeout == Some(true) {
                        run = run.strike();
                    }
                    if elem.fmt_font_family.as_deref() == Some("monospace") {
                        run = run.fonts(RunFonts::new().ascii("Courier New"));
                    }

                    paragraph = paragraph.add_run(run);
                }

                docx = docx.add_paragraph(paragraph);
                paragraph_count += 1;

                if idx % 10 == 0 {
                    let pct = 10.0 + (idx as f32 / total as f32) * 80.0;
                    progress_callback(common::long_operation::OperationProgress::new(
                        pct,
                        Some(format!("Processing paragraph {}/{}", idx + 1, total)),
                    ));
                }
            }
        }

        uow.end_transaction()?;

        progress_callback(common::long_operation::OperationProgress::new(
            90.0,
            Some("Writing DOCX file...".to_string()),
        ));

        // Write to file
        let file = std::fs::File::create(&self.dto.output_path).map_err(|e| {
            anyhow!(
                "Failed to create output file '{}': {}",
                self.dto.output_path,
                e
            )
        })?;
        docx.build()
            .pack(file)
            .map_err(|e| anyhow!("Failed to write DOCX: {}", e))?;

        progress_callback(common::long_operation::OperationProgress::new(
            100.0,
            Some("completed".to_string()),
        ));

        Ok(ExportDocxResultDto {
            file_path: self.dto.output_path.clone(),
            paragraph_count,
        })
    }
}

impl ExportDocxUseCase {
    fn render_table_docx(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        table_id: &EntityId,
    ) -> Result<docx_rs::Table> {
        use docx_rs::*;

        let table = uow
            .get_table(table_id)?
            .ok_or_else(|| anyhow!("Table not found"))?;

        let cell_ids = uow.get_table_relationship(
            table_id,
            &common::direct_access::table::TableRelationshipField::Cells,
        )?;
        let cells_opt = uow.get_table_cell_multi(&cell_ids)?;
        let mut cells: Vec<common::entities::TableCell> = cells_opt.into_iter().flatten().collect();
        cells.sort_by(|a, b| a.row.cmp(&b.row).then(a.column.cmp(&b.column)));

        // Build a grid to track which cells are covered by spans
        let rows = table.rows as usize;
        let cols = table.columns as usize;
        let mut covered = vec![vec![false; cols]; rows];

        // Build column grid widths
        let grid: Vec<usize> = table.column_widths.iter().map(|w| *w as usize).collect();

        let mut docx_rows: Vec<TableRow> = Vec::new();

        for r in 0..rows {
            let mut docx_cells: Vec<docx_rs::TableCell> = Vec::new();

            for c in 0..cols {
                if covered[r][c] {
                    // This position is covered by a row/column span from another cell.
                    // In DOCX, vertically merged continuation cells still need a <w:tc>
                    // with vMerge continue. For column spans, the cell is simply absent.
                    // Check if this is a vertical merge continuation (a cell above spans into this row)
                    let needs_vmerge_continue = r > 0 && {
                        // Look for a cell above that spans into this row
                        cells.iter().any(|cell| {
                            cell.column == c as i64
                                && cell.row < r as i64
                                && (cell.row + cell.row_span) > r as i64
                        })
                    };
                    if needs_vmerge_continue {
                        let cont_cell =
                            docx_rs::TableCell::new().vertical_merge(VMergeType::Continue);
                        docx_cells.push(cont_cell);
                    }
                    continue;
                }

                // Find the cell at this position
                let cell = cells
                    .iter()
                    .find(|cell| cell.row == r as i64 && cell.column == c as i64);

                if let Some(cell) = cell {
                    let mut docx_cell = docx_rs::TableCell::new();

                    // Apply column span
                    if cell.column_span > 1 {
                        docx_cell = docx_cell.grid_span(cell.column_span as usize);
                    }

                    // Apply vertical merge for row spans
                    if cell.row_span > 1 {
                        docx_cell = docx_cell.vertical_merge(VMergeType::Restart);
                    }

                    // Render cell content from the cell's frame
                    if let Some(cf_id) = cell.cell_frame {
                        let block_ids = uow.get_frame_relationship(
                            &cf_id,
                            &common::direct_access::frame::FrameRelationshipField::Blocks,
                        )?;
                        let blocks_opt = uow.get_block_multi(&block_ids)?;
                        let mut blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();
                        blocks.sort_by_key(|b| b.document_position);

                        for block in &blocks {
                            let block_text = block_content_via_store(block, &uow.store());
                            let elements = common::format_runs_query::inline_segments_for_block(
                                &uow.store(),
                                block.id,
                                &block_text,
                            );

                            let mut paragraph = Paragraph::new();
                            for elem in &elements {
                                let text = match &elem.content {
                                    InlineContent::Text(t) => t.clone(),
                                    InlineContent::Image { name, .. } => {
                                        format!("[Image: {}]", name)
                                    }
                                    InlineContent::Empty => String::new(),
                                };

                                if text.is_empty() {
                                    continue;
                                }

                                let mut run = Run::new().add_text(text);
                                if elem.fmt_font_bold == Some(true) {
                                    run = run.bold();
                                }
                                if elem.fmt_font_italic == Some(true) {
                                    run = run.italic();
                                }
                                if elem.fmt_font_underline == Some(true) {
                                    run = run.underline("single");
                                }
                                if elem.fmt_font_strikeout == Some(true) {
                                    run = run.strike();
                                }
                                if elem.fmt_font_family.as_deref() == Some("monospace") {
                                    run = run.fonts(RunFonts::new().ascii("Courier New"));
                                }

                                paragraph = paragraph.add_run(run);
                            }
                            docx_cell = docx_cell.add_paragraph(paragraph);
                        }
                    }

                    docx_cells.push(docx_cell);

                    // Mark spanned cells as covered
                    for sr in 0..cell.row_span as usize {
                        for sc in 0..cell.column_span as usize {
                            if sr == 0 && sc == 0 {
                                continue;
                            }
                            if r + sr < rows && c + sc < cols {
                                covered[r + sr][c + sc] = true;
                            }
                        }
                    }
                } else {
                    // Empty cell — no TableCell entity at this position
                    let docx_cell = docx_rs::TableCell::new().add_paragraph(Paragraph::new());
                    docx_cells.push(docx_cell);
                }
            }

            docx_rows.push(TableRow::new(docx_cells));
        }

        let mut docx_table = docx_rs::Table::new(docx_rows);
        if !grid.is_empty() {
            docx_table = docx_table.set_grid(grid);
        }

        Ok(docx_table)
    }
}