jumpcut 2.0.1

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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
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::{
    industry_sentence_boundary_offsets, 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, wrap_text_for_element_with_offsets,
};
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,
    avoid_page_start_parenthetical: 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,
    bottom_starts_with_parenthetical: bool,
}

impl Default for DialogueSplitPolicy {
    fn default() -> Self {
        Self {
            prefer_sentence_boundaries: true,
            prefer_fuller_top_fragment: true,
            avoid_page_start_parenthetical: 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,
    avoid_page_start_parenthetical: bool,
) -> 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,
        avoid_page_start_parenthetical,
    )
}

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,
    avoid_page_start_parenthetical: bool,
) -> Option<DialogueSplitPlan> {
    let policy = DialogueSplitPolicy {
        avoid_page_start_parenthetical,
        ..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 {
            avoids_page_start_parenthetical: !policy.avoid_page_start_parenthetical
                || !candidate.bottom_starts_with_parenthetical,
            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())
}

pub fn plan_dialogue_split_industry(
    dialogue: &DialogueUnit,
    geometry: &LayoutGeometry,
    interruption_dash_wrap: InterruptionDashWrap,
    max_top_height: f32,
    min_top_content_lines: usize,
    min_bottom_content_lines: usize,
    break_at_sentences: bool,
) -> 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_industry(
        &parts,
        geometry,
        interruption_dash_wrap,
        max_top_height,
        min_top_content_lines,
        min_bottom_content_lines,
        break_at_sentences,
    )
}

pub fn plan_dialogue_split_parts_industry(
    parts: &[DialogueTextPart],
    geometry: &LayoutGeometry,
    interruption_dash_wrap: InterruptionDashWrap,
    max_top_height: f32,
    min_top_content_lines: usize,
    min_bottom_content_lines: usize,
    break_at_sentences: bool,
) -> Option<DialogueSplitPlan> {
    let records = industry_dialogue_line_records(parts, geometry, interruption_dash_wrap);
    let split_index = industry_physical_split_index(&records, max_top_height)?;
    let bottom_record_index = industry_dialogue_handler_bottom_index(&records, split_index)?;
    let physical_boundary = industry_boundary_before(&records[bottom_record_index]);
    let boundary = if break_at_sentences {
        industry_correct_dialogue_boundary(parts, &records, bottom_record_index, physical_boundary)?
    } else {
        physical_boundary
    };
    let candidate = build_candidate(parts, geometry, interruption_dash_wrap, boundary)?;

    (candidate.plan.top_height <= max_top_height
        && candidate.top_dialogue_lines >= min_top_content_lines
        && candidate.bottom_dialogue_lines >= min_bottom_content_lines)
        .then_some(candidate.plan)
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct IndustryDialogueLineRecord {
    part_index: usize,
    kind: DialoguePartKind,
    start_offset: usize,
    paragraph_start: bool,
    line_height_bits: u32,
}

impl IndustryDialogueLineRecord {
    fn line_height(&self) -> f32 {
        f32::from_bits(self.line_height_bits)
    }
}

fn industry_dialogue_line_records(
    parts: &[DialogueTextPart],
    geometry: &LayoutGeometry,
    interruption_dash_wrap: InterruptionDashWrap,
) -> Vec<IndustryDialogueLineRecord> {
    let mut records = Vec::new();

    for (part_index, part) in parts.iter().enumerate() {
        let config = wrap_config_with_overrides(
            geometry,
            element_type_for_part_kind(part.kind.clone()),
            &part.layout_overrides,
            interruption_dash_wrap,
        );
        let line_height = line_height_for_part_kind(part.kind.clone(), geometry).to_bits();
        for (line_index, line) in wrap_text_for_element_with_offsets(&part.text, &config)
            .into_iter()
            .enumerate()
        {
            records.push(IndustryDialogueLineRecord {
                part_index,
                kind: part.kind.clone(),
                start_offset: line.start_offset,
                paragraph_start: line_index == 0,
                line_height_bits: line_height,
            });
        }
    }

    records
}

fn industry_physical_split_index(
    records: &[IndustryDialogueLineRecord],
    max_top_height: f32,
) -> Option<usize> {
    let mut height = 0.0;
    let mut split_index = 0;
    while split_index < records.len()
        && height + records[split_index].line_height() <= max_top_height
    {
        height += records[split_index].line_height();
        split_index += 1;
    }

    (split_index > 0 && split_index < records.len()).then_some(split_index)
}

fn industry_cache_record(
    records: &[IndustryDialogueLineRecord],
    split_index: usize,
    cache_index: usize,
) -> Option<&IndustryDialogueLineRecord> {
    // Cache record 5 is the physical line proposed as the first line of the
    // next page. Record 4 is immediately above the proposed break.
    let record_index = split_index as isize + cache_index as isize - 5;
    (record_index >= 0)
        .then_some(record_index as usize)
        .and_then(|index| records.get(index))
}

fn industry_is_dialogue_content(kind: &DialoguePartKind) -> bool {
    matches!(
        kind,
        DialoguePartKind::Dialogue | DialoguePartKind::Lyric | DialoguePartKind::Parenthetical
    )
}

fn industry_dialogue_handler_bottom_index(
    records: &[IndustryDialogueLineRecord],
    split_index: usize,
) -> Option<usize> {
    let line_five = industry_cache_record(records, split_index, 5)?;
    let line_six = industry_cache_record(records, split_index, 6);

    // Dialogue/Parenthetical handler, first branch: line 5 is the last line of
    // the dialogue group. Look back through cache positions 4, 3, and 2 for
    // the Character cue. If found, the handler moves the break before the cue.
    // Within this block that means the whole dialogue must move to the next page.
    if industry_is_dialogue_content(&line_five.kind)
        && !line_six.is_some_and(|line| industry_is_dialogue_content(&line.kind))
    {
        if (2..=4).any(|cache_index| {
            industry_cache_record(records, split_index, cache_index)
                .is_some_and(|line| matches!(line.kind, DialoguePartKind::Character))
        }) {
            return None;
        }

        // With no nearby Character cue, Industry compatibility moves the proposal from
        // cache line 5 to line 4 and asks sentence correction to search there.
        return split_index.checked_sub(1);
    }

    // Dialogue/Parenthetical handler, internal-group branch: Character at line
    // 3 followed by content at lines 4 and 5 is kept with the group below.
    let starts_short_group = industry_cache_record(records, split_index, 3)
        .is_some_and(|line| matches!(line.kind, DialoguePartKind::Character))
        && industry_cache_record(records, split_index, 4)
            .is_some_and(|line| industry_is_dialogue_content(&line.kind))
        && industry_is_dialogue_content(&line_five.kind);
    if starts_short_group {
        return None;
    }

    Some(split_index)
}

fn industry_boundary_before(record: &IndustryDialogueLineRecord) -> DialogueSplitBoundary {
    DialogueSplitBoundary {
        part_index: record.part_index,
        offset: record.start_offset,
        ends_sentence: false,
    }
}

fn industry_correct_dialogue_boundary(
    parts: &[DialogueTextPart],
    records: &[IndustryDialogueLineRecord],
    bottom_record_index: usize,
    physical_boundary: DialogueSplitBoundary,
) -> Option<DialogueSplitBoundary> {
    let top_line = records.get(bottom_record_index.checked_sub(1)?)?;
    let bottom_line = &records[bottom_record_index];

    // Paragraph boundaries are already valid physical boundaries. Sentence
    // correction is only applied inside one Action/Dialogue/Parenthetical
    // paragraph whose pagination types agree on both sides.
    if bottom_line.paragraph_start
        || top_line.part_index != bottom_line.part_index
        || top_line.kind != bottom_line.kind
        || !industry_is_dialogue_content(&top_line.kind)
    {
        return Some(physical_boundary);
    }

    let part = &parts[top_line.part_index];
    industry_sentence_boundary_offsets(&part.text)
        .into_iter()
        .filter(|offset| *offset > 0 && *offset <= bottom_line.start_offset)
        .max()
        .map(|offset| DialogueSplitBoundary {
            part_index: top_line.part_index,
            offset,
            ends_sentence: true,
        })
}

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);

        let supports_internal_split = matches!(
            part.kind,
            DialoguePartKind::Dialogue | DialoguePartKind::Lyric
        );
        if !supports_internal_split {
            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;
        }

        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();
    let bottom_starts_with_parenthetical = parts
        .iter()
        .zip(split_parts.iter())
        .find(|(_, split)| !split.bottom_text.is_empty())
        .is_some_and(|(part, _)| matches!(part.kind, DialoguePartKind::Parenthetical));

    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,
        bottom_starts_with_parenthetical,
    })
}

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 {
    avoids_page_start_parenthetical: bool,
    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, bool, usize, usize, usize) {
        (
            // JumpCut split ranking is applied in this order:
            // 1. avoid beginning the next page with a parenthetical
            // 2. end on a sentence boundary when possible
            // 3. prefer a substantial continuation fragment
            // 4. prefer the fuller top fragment
            // 5. prefer the more balanced split
            // 6. prefer keeping more raw content on the top page
            self.avoids_page_start_parenthetical,
            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)
}