jumpcut 1.0.0

JumpCut is a library and CLI for converting Fountain-formatted text files into FDX, HTML, JSON, text, and PDF formats.
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
use std::cmp::Ordering;
use std::collections::BTreeMap;

use crate::ElementLayoutOverrides;
use crate::pagination::margin::line_height_for_element_type;
use crate::pagination::sentence_boundary::sentence_boundary_offsets;
use crate::pagination::split_scoring::choose_best_scored_split;
use crate::pagination::wrapping::{
    ElementType, InterruptionDashWrap, WrapConfig, wrap_config_with_overrides,
    wrap_text_for_element,
};
use crate::pagination::{DialoguePartKind, DialogueUnit, LayoutGeometry};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DialoguePartSplitLines {
    pub top_text: String,
    pub bottom_text: String,
    pub top_end_offset: usize,
    pub bottom_start_offset: usize,
    pub top_lines: Vec<String>,
    pub bottom_lines: Vec<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DialogueSplitPlan {
    pub top_line_count: usize,
    pub bottom_line_count: usize,
    pub top_height: f32,
    pub bottom_height: f32,
    pub ends_sentence: bool,
    pub parts: Vec<DialoguePartSplitLines>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DialogueTextPart {
    pub kind: DialoguePartKind,
    pub text: String,
    pub layout_overrides: ElementLayoutOverrides,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DialogueSplitPolicy {
    prefer_sentence_boundaries: bool,
    prefer_fuller_top_fragment: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DialogueSplitBoundary {
    part_index: usize,
    offset: usize,
    ends_sentence: bool,
}

#[derive(Debug, Clone, PartialEq)]
struct DialogueSplitCandidate {
    plan: DialogueSplitPlan,
    top_dialogue_lines: usize,
    bottom_dialogue_lines: usize,
    top_spoken_lines: usize,
    bottom_spoken_lines: usize,
    bottom_first_spoken_line_chars: usize,
    bottom_terminal_spoken_line_chars: usize,
    mid_part_sentence_boundary_eligible: bool,
    same_top_line_extension: bool,
    boundary_part_index: usize,
    boundary_offset: usize,
    ends_sentence: bool,
    top_content_bytes: usize,
}

impl Default for DialogueSplitPolicy {
    fn default() -> Self {
        Self {
            prefer_sentence_boundaries: true,
            prefer_fuller_top_fragment: true,
        }
    }
}

pub fn plan_dialogue_split(
    dialogue: &DialogueUnit,
    geometry: &LayoutGeometry,
    interruption_dash_wrap: InterruptionDashWrap,
    max_top_height: f32,
    min_top_content_lines: usize,
    min_bottom_content_lines: usize,
) -> Option<DialogueSplitPlan> {
    let parts = dialogue
        .parts
        .iter()
        .map(|part| DialogueTextPart {
            kind: part.kind.clone(),
            text: part.text.clone(),
            layout_overrides: part.render_attributes.layout_overrides.clone(),
        })
        .collect::<Vec<_>>();
    plan_dialogue_split_parts(
        dialogue,
        &parts,
        geometry,
        interruption_dash_wrap,
        max_top_height,
        min_top_content_lines,
        min_bottom_content_lines,
    )
}

pub fn plan_dialogue_split_parts(
    _dialogue: &DialogueUnit,
    parts: &[DialogueTextPart],
    geometry: &LayoutGeometry,
    interruption_dash_wrap: InterruptionDashWrap,
    max_top_height: f32,
    min_top_content_lines: usize,
    min_bottom_content_lines: usize,
) -> Option<DialogueSplitPlan> {
    let policy = DialogueSplitPolicy::default();
    let candidates = generate_dialogue_split_candidates(parts, geometry, interruption_dash_wrap);

    let winner = choose_best_scored_split(0..candidates.len(), |candidate_index| {
        let candidate = &candidates[candidate_index];
        if candidate.plan.top_height > max_top_height {
            return None;
        }

        // The planner enforces semantic minima in content-line units:
        // wrapped dialogue, lyric, and parenthetical lines only. The paginator
        // separately handles whether the page has enough physical space to host
        // any split at all.
        if candidate.top_dialogue_lines < min_top_content_lines
            || candidate.bottom_dialogue_lines < min_bottom_content_lines
        {
            return None;
        }

        Some(SplitScore {
            ends_sentence: policy.prefer_sentence_boundaries && candidate.ends_sentence,
            substantial_bottom: substantial_bottom(
                candidate.bottom_spoken_lines,
                candidate.bottom_first_spoken_line_chars,
                candidate.bottom_terminal_spoken_line_chars,
                candidate.mid_part_sentence_boundary_eligible,
                candidate.same_top_line_extension,
            ),
            fuller_top_fragment: if policy.prefer_fuller_top_fragment {
                candidate.plan.top_line_count
            } else {
                0
            },
            balance_score: balance_score(
                candidate.top_dialogue_lines,
                candidate.bottom_dialogue_lines,
            ),
            top_content_bytes: candidate.top_content_bytes,
        })
    });

    winner.map(|candidate_index| candidates[candidate_index].plan.clone())
}

fn generate_dialogue_split_candidates(
    parts: &[DialogueTextPart],
    geometry: &LayoutGeometry,
    interruption_dash_wrap: InterruptionDashWrap,
) -> Vec<DialogueSplitCandidate> {
    let mut boundaries: BTreeMap<(usize, usize), bool> = BTreeMap::new();

    for (part_index, part) in parts.iter().enumerate() {
        // Part-end boundaries are always candidates but never score as sentence endings.
        boundaries
            .entry((part_index, part.text.len()))
            .or_insert(false);

        if !matches!(
            part.kind,
            DialoguePartKind::Dialogue | DialoguePartKind::Lyric
        ) {
            continue;
        }

        let config = wrap_config_with_overrides(
            geometry,
            element_type_for_part_kind(part.kind.clone()),
            &part.layout_overrides,
            interruption_dash_wrap,
        );
        let total_wrapped_lines = wrap_text_for_element(&part.text, &config).len();

        // Only allow mid-text sentence splits for parts with at least 3 wrapped lines.
        // A 2-line part is too compact to split cleanly.
        if total_wrapped_lines < 3 {
            continue;
        }

        // FD only splits dialogue at sentence boundaries, never at arbitrary
        // wrapped-line breaks.
        for offset in sentence_boundary_offsets(&part.text) {
            boundaries
                .entry((part_index, offset))
                .and_modify(|ends_sentence| *ends_sentence = true)
                .or_insert(true);
        }
    }

    let mut candidates = boundaries
        .into_iter()
        .filter_map(|((part_index, offset), ends_sentence)| {
            build_candidate(
                parts,
                geometry,
                interruption_dash_wrap,
                DialogueSplitBoundary {
                    part_index,
                    offset,
                    ends_sentence,
                },
            )
        })
        .collect::<Vec<_>>();

    for i in 0..candidates.len() {
        let candidate = &candidates[i];
        let same_top_line_extension = candidate.mid_part_sentence_boundary_eligible
            && candidates.iter().any(|earlier| {
                earlier.ends_sentence
                    && earlier.boundary_part_index == candidate.boundary_part_index
                    && earlier.boundary_offset < candidate.boundary_offset
                    && earlier.plan.top_line_count == candidate.plan.top_line_count
            });
        candidates[i].same_top_line_extension = same_top_line_extension;
    }

    candidates
}

fn build_candidate(
    parts: &[DialogueTextPart],
    geometry: &LayoutGeometry,
    interruption_dash_wrap: InterruptionDashWrap,
    boundary: DialogueSplitBoundary,
) -> Option<DialogueSplitCandidate> {
    let mut top_line_count = 0;
    let mut bottom_line_count = 0;
    let mut top_height = 0.0;
    let mut bottom_height = 0.0;
    let mut top_dialogue_lines = 0;
    let mut bottom_dialogue_lines = 0;
    let mut top_spoken_lines = 0;
    let mut bottom_spoken_lines = 0;
    let mut bottom_first_spoken_line_chars = 0;
    let mut bottom_terminal_spoken_line_chars = 0;
    let mut mid_part_sentence_boundary_eligible = false;
    let mut split_parts = Vec::with_capacity(parts.len());

    for (part_index, part) in parts.iter().enumerate() {
        let (top_text, bottom_text) = split_part_text(&part.text, part_index, boundary);
        let config = wrap_config_with_overrides(
            geometry,
            element_type_for_part_kind(part.kind.clone()),
            &part.layout_overrides,
            interruption_dash_wrap,
        );
        let top_lines = wrap_fragment_lines(top_text, &config);
        let bottom_lines = wrap_fragment_lines(bottom_text, &config);
        let line_height = line_height_for_part_kind(part.kind.clone(), geometry);

        top_line_count += top_lines.len();
        bottom_line_count += bottom_lines.len();
        top_height += top_lines.len() as f32 * line_height;
        bottom_height += bottom_lines.len() as f32 * line_height;

        if matches!(
            part.kind,
            DialoguePartKind::Dialogue | DialoguePartKind::Lyric | DialoguePartKind::Parenthetical
        ) {
            top_dialogue_lines += top_lines.len();
            bottom_dialogue_lines += bottom_lines.len();
        }

        if matches!(
            part.kind,
            DialoguePartKind::Dialogue | DialoguePartKind::Lyric
        ) {
            top_spoken_lines += top_lines.len();
            bottom_spoken_lines += bottom_lines.len();
            if let Some(first_line) = bottom_lines.first() {
                bottom_first_spoken_line_chars = first_line.trim_end().chars().count();
            }
            if let Some(last_line) = bottom_lines.last() {
                bottom_terminal_spoken_line_chars = last_line.trim_end().chars().count();
            }
            mid_part_sentence_boundary_eligible = boundary.ends_sentence
                && part_index == boundary.part_index
                && boundary.offset < part.text.len();
        }

        split_parts.push(DialoguePartSplitLines {
            top_text: top_text.to_string(),
            bottom_text: bottom_text.to_string(),
            top_end_offset: top_text.len(),
            bottom_start_offset: part.text.len() - bottom_text.len(),
            top_lines,
            bottom_lines,
        });
    }

    if top_line_count == 0 || bottom_line_count == 0 {
        return None;
    }

    let top_content_bytes: usize = split_parts.iter().map(|p| p.top_text.len()).sum();

    Some(DialogueSplitCandidate {
        plan: DialogueSplitPlan {
            top_line_count,
            bottom_line_count,
            top_height,
            bottom_height,
            ends_sentence: boundary.ends_sentence,
            parts: split_parts,
        },
        top_dialogue_lines,
        bottom_dialogue_lines,
        top_spoken_lines,
        bottom_spoken_lines,
        bottom_first_spoken_line_chars,
        bottom_terminal_spoken_line_chars,
        mid_part_sentence_boundary_eligible,
        same_top_line_extension: false,
        boundary_part_index: boundary.part_index,
        boundary_offset: boundary.offset,
        ends_sentence: boundary.ends_sentence,
        top_content_bytes,
    })
}

fn split_part_text(text: &str, part_index: usize, boundary: DialogueSplitBoundary) -> (&str, &str) {
    if part_index < boundary.part_index {
        return (text, "");
    }

    if part_index > boundary.part_index {
        return ("", text);
    }

    text.split_at(boundary.offset)
}

fn wrap_fragment_lines(text: &str, config: &WrapConfig) -> Vec<String> {
    if text.is_empty() {
        Vec::new()
    } else {
        wrap_text_for_element(text, config)
    }
}

fn element_type_for_part_kind(kind: DialoguePartKind) -> ElementType {
    match kind {
        DialoguePartKind::Character => ElementType::Character,
        DialoguePartKind::Parenthetical => ElementType::Parenthetical,
        DialoguePartKind::Dialogue => ElementType::Dialogue,
        DialoguePartKind::Lyric => ElementType::Lyric,
    }
}

fn line_height_for_part_kind(kind: DialoguePartKind, geometry: &LayoutGeometry) -> f32 {
    line_height_for_element_type(geometry, element_type_for_part_kind(kind))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SplitScore {
    ends_sentence: bool,
    fuller_top_fragment: usize,
    substantial_bottom: bool,
    balance_score: usize,
    top_content_bytes: usize,
}

impl SplitScore {
    fn priority_tuple(&self) -> (bool, bool, usize, usize, usize) {
        (
            // Final Draft-like split ranking is applied in this order:
            // 1. end on a sentence boundary when possible
            // 2. prefer a substantial continuation fragment
            // 3. prefer the fuller top fragment
            // 4. prefer the more balanced split
            // 5. prefer keeping more raw content on the top page
            self.ends_sentence,
            self.substantial_bottom,
            self.fuller_top_fragment,
            self.balance_score,
            self.top_content_bytes,
        )
    }
}

impl PartialOrd for SplitScore {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SplitScore {
    fn cmp(&self, other: &Self) -> Ordering {
        self.priority_tuple().cmp(&other.priority_tuple())
    }
}

fn balance_score(top_dialogue_lines: usize, bottom_dialogue_lines: usize) -> usize {
    usize::MAX - top_dialogue_lines.abs_diff(bottom_dialogue_lines)
}

fn substantial_bottom(
    bottom_dialogue_lines: usize,
    bottom_first_spoken_line_chars: usize,
    bottom_terminal_spoken_line_chars: usize,
    mid_part_sentence_boundary_eligible: bool,
    same_top_line_extension: bool,
) -> bool {
    bottom_dialogue_lines >= 3
        || (mid_part_sentence_boundary_eligible && same_top_line_extension)
        || (mid_part_sentence_boundary_eligible
            && bottom_dialogue_lines >= 1
            && bottom_first_spoken_line_chars >= 16
            && bottom_terminal_spoken_line_chars >= 16)
}