use std::ops::Range;
use super::line_break::first_char;
use super::options::{Indent, Vars};
use super::page::{Cue, ICON_CHAR};
use crate::markup::{Item, Script};
use crate::text::grapheme::graphemes;
use crate::text::kinsoku::{is_closing_punct, is_opening_bracket};
use crate::text::line_class::{line_class, LineClass};
#[derive(Debug, Clone)]
pub(super) struct Cluster {
pub(super) ch: char,
pub(super) tail: String,
pub(super) source: Range<usize>,
pub(super) var: Option<usize>,
}
#[derive(Clone, Copy)]
enum Origin<'a> {
Chars(&'a [Range<usize>]),
Var(&'a Range<usize>, usize),
}
fn clusters(s: &str, origin: Origin<'_>) -> Vec<Cluster> {
let mut at = 0;
graphemes(s)
.into_iter()
.map(|g| {
let n = g.chars().count();
let mut it = g.chars();
let ch = it.next().expect("書記素クラスタは1文字以上");
let (source, var) = match origin {
Origin::Chars(src) => {
let first = src.get(at).map_or(0, |r| r.start);
let last = src.get(at + n - 1).map_or(first, |r| r.end);
(first..last, None)
}
Origin::Var(r, v) => (r.clone(), Some(v)),
};
at += n;
Cluster {
ch,
tail: it.as_str().to_string(),
source,
var,
}
})
.collect()
}
#[derive(Debug, Clone)]
pub(super) struct Unit {
pub(super) chars: Vec<Cluster>,
pub(super) style: usize,
pub(super) ruby: Option<String>,
pub(super) tcy: bool,
pub(super) icon: Option<(String, f32)>,
pub(super) cues: Vec<Cue>,
pub(super) glue: bool,
}
#[derive(Debug, Default)]
pub(super) struct Paragraph {
pub(super) units: Vec<Unit>,
pub(super) tail_cues: Vec<Cue>,
pub(super) kind: ParaKind,
text: Vec<(Cluster, usize, Vec<Cue>)>,
}
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub(super) enum ParaKind {
#[default]
Plain,
ManualIndent,
Bracket,
Continued,
}
fn is_closing_bracket(ch: char) -> bool {
is_closing_punct(ch) && !matches!(ch, '、' | '。' | ',' | '.')
}
fn classify_paragraphs(pages: &mut [PageSrc]) {
let mut depth = 0usize;
for para in pages.iter_mut().flat_map(|p| p.paragraphs.iter_mut()) {
let first = para.units.first().map(first_char);
if depth > 0 && first.is_some_and(is_opening_bracket) {
depth = 0;
}
para.kind = match first {
_ if depth > 0 => ParaKind::Continued,
Some(c) if is_opening_bracket(c) => ParaKind::Bracket,
Some('\u{3000}') => ParaKind::ManualIndent,
_ => ParaKind::Plain,
};
for c in para.units.iter().flat_map(|u| &u.chars) {
if is_opening_bracket(c.ch) {
depth += 1;
} else if is_closing_bracket(c.ch) {
depth = depth.saturating_sub(1);
}
}
}
}
impl Indent {
pub(super) fn of(&self, kind: ParaKind) -> (f32, f32) {
let (a, b) = match kind {
ParaKind::Plain => (self.first, self.rest),
ParaKind::ManualIndent => (0.0, self.rest),
ParaKind::Bracket => (self.bracket_first, self.bracket_rest),
ParaKind::Continued => (self.bracket_rest, self.bracket_rest),
};
let ok = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
(ok(a), ok(b))
}
}
#[derive(Default)]
pub(super) struct PageSrc {
pub(super) paragraphs: Vec<Paragraph>,
}
pub(super) fn split_pages(
script: &Script,
vars: &Vars,
missing: &mut Vec<String>,
used: &mut Vec<String>,
) -> Vec<PageSrc> {
let mut pages = vec![PageSrc::default()];
let mut para = Paragraph::default();
let mut pending: Vec<Cue> = Vec::new();
fn push_text(
text: &str,
origin: Origin<'_>,
style: usize,
para: &mut Paragraph,
pending: &mut Vec<Cue>,
) {
for c in clusters(text, origin) {
para.text.push((c, style, std::mem::take(pending)));
}
}
fn flush_text(para: &mut Paragraph) {
let cs = std::mem::take(&mut para.text);
let class = |k: usize| cs.get(k).map(|c| line_class(c.0.ch));
let digit = |c: Option<LineClass>| c == Some(LineClass::Numeric);
let mut join = vec![false; cs.len()];
let mut last: Option<LineClass> = None;
for k in 0..cs.len() {
let (c, kind, next) = (cs[k].0.ch, line_class(cs[k].0.ch), class(k + 1));
let in_word = matches!(kind, LineClass::Alpha | LineClass::Numeric)
|| (matches!(c, '\'' | '’') && last == Some(LineClass::Alpha))
|| (matches!(c, '.' | ',' | ':' | '/' | '-') && digit(last) && digit(next))
|| (kind == LineClass::Prefix && digit(next))
|| (kind == LineClass::Postfix && digit(last));
if in_word {
join[k] = last.is_some();
last = Some(kind);
} else if kind == LineClass::Hyphen && last == Some(LineClass::Alpha) {
join[k] = true;
last = None;
} else {
last = None;
}
}
for (k, (c, style, cues)) in cs.into_iter().enumerate() {
if join[k] {
if let Some(u) = para
.units
.last_mut()
.filter(|u| u.style == style && cues.is_empty())
{
u.chars.push(c);
continue;
}
}
para.units.push(Unit {
chars: vec![c],
style,
ruby: None,
tcy: false,
icon: None,
cues,
glue: join[k],
});
}
}
for item in &script.items {
if !matches!(
item,
Item::Text { .. } | Item::Var { .. } | Item::Wait(_) | Item::Click | Item::Event(_)
) {
flush_text(&mut para);
}
match item {
Item::Text {
text,
style,
source,
} => push_text(text, Origin::Chars(source), *style, &mut para, &mut pending),
Item::Var {
name,
style,
source,
} => {
let id = used.iter().position(|v| v == name).unwrap_or_else(|| {
used.push(name.clone());
used.len() - 1
});
let value = match vars.get(name) {
Some(v) => v.clone(),
None => {
if !missing.contains(name) {
missing.push(name.clone());
}
format!("[var {name}]")
}
};
let value: String = value
.replace("\r\n", "\n")
.chars()
.filter_map(|c| match c {
'\n' => Some('\n'),
'\t' => Some(' '),
c if c.is_control() => None,
c => Some(c),
})
.collect();
for (k, part) in value.split('\n').enumerate() {
if k > 0 {
flush_text(&mut para);
para.tail_cues = std::mem::take(&mut pending);
pages
.last_mut()
.expect("ページは1つ以上")
.paragraphs
.push(std::mem::take(&mut para));
}
push_text(
part,
Origin::Var(source, id),
*style,
&mut para,
&mut pending,
);
}
}
Item::Ruby {
base,
reading,
style,
source,
} => para.units.push(Unit {
chars: clusters(base, Origin::Chars(source)),
style: *style,
ruby: Some(reading.clone()),
tcy: false,
icon: None,
cues: std::mem::take(&mut pending),
glue: false,
}),
Item::Tcy {
text,
style,
source,
} => para.units.push(Unit {
chars: clusters(text, Origin::Chars(source)),
style: *style,
ruby: None,
tcy: true,
icon: None,
cues: std::mem::take(&mut pending),
glue: false,
}),
Item::Icon {
id,
width,
style,
source,
} => para.units.push(Unit {
chars: vec![Cluster {
ch: ICON_CHAR,
tail: String::new(),
source: source.clone(),
var: None,
}],
style: *style,
ruby: None,
tcy: false,
icon: Some((id.clone(), *width)),
cues: std::mem::take(&mut pending),
glue: false,
}),
Item::Wait(s) => pending.push(Cue::Wait(*s)),
Item::Click => pending.push(Cue::Click),
Item::Event(e) => pending.push(Cue::Event(e.clone())),
Item::Break => {
para.tail_cues = std::mem::take(&mut pending);
pages
.last_mut()
.expect("ページは1つ以上")
.paragraphs
.push(std::mem::take(&mut para));
}
Item::Page => {
para.tail_cues = std::mem::take(&mut pending);
pages
.last_mut()
.expect("ページは1つ以上")
.paragraphs
.push(std::mem::take(&mut para));
pages.push(PageSrc::default());
}
}
}
flush_text(&mut para);
para.tail_cues = std::mem::take(&mut pending);
let last = pages.last_mut().expect("ページは1つ以上");
if !para.units.is_empty() || !para.tail_cues.is_empty() || last.paragraphs.is_empty() {
last.paragraphs.push(para);
}
if pages.len() > 1 && pages.last().is_some_and(|p| p.is_blank()) {
pages.pop();
}
classify_paragraphs(&mut pages);
pages
}
impl PageSrc {
fn is_blank(&self) -> bool {
self.paragraphs
.iter()
.all(|p| p.units.is_empty() && p.tail_cues.is_empty())
}
}