text-document-formatting 1.10.2

Undoable text and block formatting use cases for text-document
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
use crate::SetTextFormatDto;
use anyhow::{Result, anyhow};
use common::database::CommandUnitOfWork;
use common::database::rope_helpers::{block_char_length, block_char_to_byte_in_block};
use common::direct_access::document::document_repository::DocumentRelationshipField;
use common::direct_access::frame::frame_repository::FrameRelationshipField;
use common::direct_access::root::root_repository::RootRelationshipField;
use common::entities::{Block, Document, Frame, Root};
use common::format_runs::{
    CharacterFormat, FormatRun, capture_image_formats_in_range, capture_runs_in_range,
    debug_assert_well_formed, splice_range,
};
use common::types::{EntityId, ROOT_ENTITY_ID};
use common::undo_redo::UndoRedoCommand;
use std::any::Any;

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

#[macros::uow_action(entity = "Root", action = "Get")]
#[macros::uow_action(entity = "Root", action = "GetRelationship")]
#[macros::uow_action(entity = "Document", action = "Get")]
#[macros::uow_action(entity = "Document", action = "GetRelationship")]
#[macros::uow_action(entity = "Frame", action = "Get")]
#[macros::uow_action(entity = "Frame", action = "GetRelationship")]
#[macros::uow_action(entity = "Block", action = "Get")]
#[macros::uow_action(entity = "Block", action = "GetMulti")]
#[macros::uow_action(entity = "Block", action = "GetRelationship")]
pub trait SetTextFormatUnitOfWorkTrait: CommandUnitOfWork {}

/// Per-block captured state for hand-rolled undo. Built during the
/// mutation pass; consumed by `undo()` to restore the prior state
/// without paying the cost of a full RopeStoreSnapshot.
#[derive(Clone, Debug)]
struct BlockFormatInverse {
    block_id: EntityId,
    byte_range: (u32, u32),
    prior_runs: Vec<FormatRun>,
    prior_image_formats: Vec<(u32, CharacterFormat)>,
}

fn underline_style_to_entity(s: &crate::dtos::UnderlineStyle) -> common::entities::UnderlineStyle {
    match s {
        crate::dtos::UnderlineStyle::NoUnderline => common::entities::UnderlineStyle::NoUnderline,
        crate::dtos::UnderlineStyle::SingleUnderline => {
            common::entities::UnderlineStyle::SingleUnderline
        }
        crate::dtos::UnderlineStyle::DashUnderline => {
            common::entities::UnderlineStyle::DashUnderline
        }
        crate::dtos::UnderlineStyle::DotLine => common::entities::UnderlineStyle::DotLine,
        crate::dtos::UnderlineStyle::DashDotLine => common::entities::UnderlineStyle::DashDotLine,
        crate::dtos::UnderlineStyle::DashDotDotLine => {
            common::entities::UnderlineStyle::DashDotDotLine
        }
        crate::dtos::UnderlineStyle::WaveUnderline => {
            common::entities::UnderlineStyle::WaveUnderline
        }
        crate::dtos::UnderlineStyle::SpellCheckUnderline => {
            common::entities::UnderlineStyle::SpellCheckUnderline
        }
    }
}

/// DTO enum → entity enum. Shared with `merge_text_format_uc`, which carries
/// the same field: a mapping table, not business logic, so sharing it does not
/// make one use case depend on another. It lives here because `lib.rs` and
/// `use_cases.rs` are both generated and a shared module would mean hand-editing
/// a third generated file.
pub(crate) fn vertical_alignment_to_entity(
    v: &crate::dtos::CharVerticalAlignment,
) -> common::entities::CharVerticalAlignment {
    match v {
        crate::dtos::CharVerticalAlignment::Normal => {
            common::entities::CharVerticalAlignment::Normal
        }
        crate::dtos::CharVerticalAlignment::SuperScript => {
            common::entities::CharVerticalAlignment::SuperScript
        }
        crate::dtos::CharVerticalAlignment::SubScript => {
            common::entities::CharVerticalAlignment::SubScript
        }
        crate::dtos::CharVerticalAlignment::Middle => {
            common::entities::CharVerticalAlignment::Middle
        }
        crate::dtos::CharVerticalAlignment::Bottom => {
            common::entities::CharVerticalAlignment::Bottom
        }
        crate::dtos::CharVerticalAlignment::Top => common::entities::CharVerticalAlignment::Top,
        crate::dtos::CharVerticalAlignment::Baseline => {
            common::entities::CharVerticalAlignment::Baseline
        }
    }
}

/// Apply a SetTextFormatDto onto a CharacterFormat, overwriting only the
/// fields the dto sets to `Some(_)`. Returns the merged format.
fn merge_dto(base: &CharacterFormat, dto: &SetTextFormatDto) -> CharacterFormat {
    let mut out = base.clone();
    if let Some(ref v) = dto.font_family {
        out.font_family = Some(v.clone());
    }
    if let Some(v) = dto.font_point_size {
        out.font_point_size = Some(v);
    }
    if let Some(v) = dto.font_weight {
        out.font_weight = Some(v);
    }
    if let Some(v) = dto.font_bold {
        out.font_bold = Some(v);
    }
    if let Some(v) = dto.font_italic {
        out.font_italic = Some(v);
    }
    if let Some(v) = dto.font_underline {
        out.font_underline = Some(v);
    }
    if let Some(v) = dto.font_overline {
        out.font_overline = Some(v);
    }
    if let Some(v) = dto.font_strikeout {
        out.font_strikeout = Some(v);
    }
    if let Some(v) = dto.letter_spacing {
        out.letter_spacing = Some(v);
    }
    if let Some(v) = dto.word_spacing {
        out.word_spacing = Some(v);
    }
    if let Some(ref v) = dto.underline_style {
        out.underline_style = Some(underline_style_to_entity(v));
    }
    if let Some(ref v) = dto.vertical_alignment {
        out.vertical_alignment = Some(vertical_alignment_to_entity(v));
    }
    apply_link(&mut out, dto.clear_link, dto.anchor_href.as_deref());
    out
}

/// Write a hyperlink onto a character format, or take one off.
///
/// `is_anchor` is derived rather than carried: every importer sets it to
/// `Some(true)` exactly when a destination is present, so deriving it here is
/// the only way the two cannot fall out of step. An empty destination is
/// treated as "no change", following the same rule `font_family` already
/// follows in both merge paths.
///
/// Shared by [`set_text_format`](super::set_text_format_uc) and
/// [`merge_text_format`](super::merge_text_format_uc) so the two cannot
/// disagree about what applying a link means.
pub(crate) fn apply_link(out: &mut CharacterFormat, clear: bool, href: Option<&str>) {
    if clear {
        out.anchor_href = None;
        out.is_anchor = None;
        out.anchor_names = Vec::new();
        out.tooltip = None;
    } else if let Some(href) = href
        && !href.is_empty()
    {
        out.anchor_href = Some(href.to_string());
        out.is_anchor = Some(true);
    }
}

/// Build the replacement run list covering `[byte_start..byte_end)` of a
/// block, merging the dto's fields onto every existing run (and gaps
/// between runs default to `CharacterFormat::default()` before merging).
fn build_replacement_runs(
    existing_runs: &[FormatRun],
    byte_start: u32,
    byte_end: u32,
    dto: &SetTextFormatDto,
) -> Vec<FormatRun> {
    let mut out: Vec<FormatRun> = Vec::new();
    let mut cursor = byte_start;
    for run in existing_runs {
        if run.byte_end <= byte_start || run.byte_start >= byte_end {
            continue;
        }
        let overlap_start = std::cmp::max(run.byte_start, byte_start);
        let overlap_end = std::cmp::min(run.byte_end, byte_end);
        if overlap_start > cursor {
            out.push(FormatRun {
                byte_start: cursor,
                byte_end: overlap_start,
                format: merge_dto(&CharacterFormat::default(), dto),
            });
        }
        out.push(FormatRun {
            byte_start: overlap_start,
            byte_end: overlap_end,
            format: merge_dto(&run.format, dto),
        });
        cursor = overlap_end;
    }
    if cursor < byte_end {
        out.push(FormatRun {
            byte_start: cursor,
            byte_end,
            format: merge_dto(&CharacterFormat::default(), dto),
        });
    }
    out
}

fn execute_set_text_format(
    uow: &mut Box<dyn SetTextFormatUnitOfWorkTrait>,
    dto: &SetTextFormatDto,
) -> Result<Vec<BlockFormatInverse>> {
    // Get Root -> 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, &RootRelationshipField::Document)?;
    let doc_id = *doc_ids
        .first()
        .ok_or_else(|| anyhow!("Root has no document"))?;

    let _document = uow
        .get_document(&doc_id)?
        .ok_or_else(|| anyhow!("Document not found"))?;

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

    let mut all_block_ids = Vec::new();
    for fid in &frame_ids {
        let block_ids = uow.get_frame_relationship(fid, &FrameRelationshipField::Blocks)?;
        all_block_ids.extend(block_ids);
    }

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

    let range_start = std::cmp::min(dto.position, dto.anchor);
    let range_end = std::cmp::max(dto.position, dto.anchor);

    let mut inverse: Vec<BlockFormatInverse> = Vec::new();

    if range_start == range_end {
        return Ok(inverse);
    }

    let store = uow.store();
    for block in &blocks {
        let block_start = block.document_position;
        let block_end = block_start + block_char_length(block, &store);

        if block_end <= range_start || block_start >= range_end {
            continue;
        }

        // Char-relative range within this block.
        let local_char_start = std::cmp::max(0, range_start - block_start) as usize;
        let local_char_end =
            std::cmp::min(block_char_length(block, &store), range_end - block_start) as usize;

        // Rope-native char->byte translation. block_char_to_byte_in_block
        // clamps char offsets to the block's logical length, so no
        // separate plain_text_len/min clamp is needed here.
        let (byte_start, content_byte_len) =
            block_char_to_byte_in_block(&store, block.id, local_char_start);
        let (byte_end, _) = block_char_to_byte_in_block(&store, block.id, local_char_end);

        if byte_start >= byte_end {
            continue;
        }

        // Capture prior state before mutation.
        let prior_runs = {
            let runs_map = store.format_runs.read();
            runs_map
                .get(&block.id)
                .map(|runs| capture_runs_in_range(runs, byte_start, byte_end))
                .unwrap_or_default()
        };
        let prior_image_formats = {
            let images_map = store.block_images.read();
            images_map
                .get(&block.id)
                .map(|images| capture_image_formats_in_range(images, byte_start, byte_end))
                .unwrap_or_default()
        };

        // Update format runs over the byte range.
        {
            let mut runs_map = store.format_runs.write();
            let runs = runs_map.entry(block.id).or_default();
            let replacement = build_replacement_runs(runs, byte_start, byte_end, dto);
            splice_range(runs, byte_start..byte_end, replacement);
            debug_assert_well_formed(runs, content_byte_len);
        }

        // Update image anchor formats. An image at `byte_offset` is in the
        // selection if its byte_offset is inside [byte_start..byte_end].
        {
            let mut images_map = store.block_images.write();
            if let Some(images) = images_map.get_mut(&block.id) {
                for img in images.iter_mut() {
                    if img.byte_offset >= byte_start && img.byte_offset < byte_end {
                        img.format = merge_dto(&img.format, dto);
                    }
                }
            }
        }

        inverse.push(BlockFormatInverse {
            block_id: block.id,
            byte_range: (byte_start, byte_end),
            prior_runs,
            prior_image_formats,
        });
    }

    Ok(inverse)
}

/// Restore the prior format-run and image-format state captured during
/// the forward mutation. Splices the captured runs back into each
/// affected block's byte range and restores per-image formats.
fn apply_inverse(
    uow: &mut Box<dyn SetTextFormatUnitOfWorkTrait>,
    inverse: &[BlockFormatInverse],
) -> Result<()> {
    let store = uow.store();
    for entry in inverse {
        {
            let mut runs_map = store.format_runs.write();
            let runs = runs_map.entry(entry.block_id).or_default();
            splice_range(
                runs,
                entry.byte_range.0..entry.byte_range.1,
                entry.prior_runs.clone(),
            );
        }
        {
            let mut images_map = store.block_images.write();
            if let Some(images) = images_map.get_mut(&entry.block_id) {
                for (byte_offset, format) in &entry.prior_image_formats {
                    if let Some(img) = images.iter_mut().find(|i| i.byte_offset == *byte_offset) {
                        img.format = format.clone();
                    }
                }
            }
        }
    }
    Ok(())
}

pub struct SetTextFormatUseCase {
    uow_factory: Box<dyn SetTextFormatUnitOfWorkFactoryTrait>,
    inverse: Option<Vec<BlockFormatInverse>>,
    last_dto: Option<SetTextFormatDto>,
}

impl SetTextFormatUseCase {
    pub fn new(uow_factory: Box<dyn SetTextFormatUnitOfWorkFactoryTrait>) -> Self {
        SetTextFormatUseCase {
            uow_factory,
            inverse: None,
            last_dto: None,
        }
    }

    pub fn execute(&mut self, dto: &SetTextFormatDto) -> Result<()> {
        let mut uow = self.uow_factory.create();
        uow.begin_transaction()?;

        let inverse = execute_set_text_format(&mut uow, dto)?;
        self.inverse = Some(inverse);
        self.last_dto = Some(dto.clone());

        uow.commit()?;
        Ok(())
    }
}

impl UndoRedoCommand for SetTextFormatUseCase {
    fn undo(&mut self) -> Result<()> {
        let inverse = self
            .inverse
            .as_ref()
            .ok_or_else(|| anyhow!("No inverse data available for undo"))?
            .clone();

        let mut uow = self.uow_factory.create();
        uow.begin_transaction()?;
        apply_inverse(&mut uow, &inverse)?;
        uow.commit()?;
        Ok(())
    }

    fn redo(&mut self) -> Result<()> {
        let dto = self
            .last_dto
            .as_ref()
            .ok_or_else(|| anyhow!("No DTO available for redo"))?
            .clone();

        let mut uow = self.uow_factory.create();
        uow.begin_transaction()?;
        let inverse = execute_set_text_format(&mut uow, &dto)?;
        self.inverse = Some(inverse);
        uow.commit()?;
        Ok(())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}