use std::{
cell::RefCell,
collections::HashMap,
rc::Rc,
sync::{Arc, Mutex, OnceLock},
};
use arc_motion::{PathPoint, PolylinePath, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Typography};
use gpui_kit::{
App, Bounds, ContentMask, ElementId, Hsla, InteractiveElement as _, IntoElement,
MouseMoveEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window, canvas, div, point, prelude::*, px, size,
};
use super::glyph_outline::{Outline, with_face};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldStyle {
#[default]
Paper,
Blinds,
Flip,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldSplit {
#[default]
Char,
Word,
Line,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldHinge {
#[default]
Top,
Bottom,
Left,
Right,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldTrigger {
#[default]
Mount,
Hover,
Scroll,
Loop,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldStaggerFrom {
#[default]
Start,
Center,
End,
Edges,
Random,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldEase {
#[default]
Power3Out,
Power2Out,
Power1Out,
Linear,
}
impl FoldEase {
pub fn sample(self, t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
match self {
Self::Linear => t,
Self::Power1Out => 1.0 - (1.0 - t).powi(2),
Self::Power2Out => 1.0 - (1.0 - t).powi(3),
Self::Power3Out => 1.0 - (1.0 - t).powi(4),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct FoldTextConfig {
pub fold_style: FoldStyle,
pub split_by: FoldSplit,
pub hinge: FoldHinge,
pub trigger: FoldTrigger,
pub stagger_from: FoldStaggerFrom,
pub fold_angle: f32,
pub duration: f64,
pub stagger: f64,
pub ease: FoldEase,
pub perspective: f32,
pub crease_shading: f32,
pub loop_delay: f64,
pub hover_refold: bool,
pub refold_radius: f32,
pub refold_angle: f32,
pub font_size: f32,
pub font_weight: u16,
pub letter_spacing: f32,
pub font_family: String,
pub color: Option<Hsla>,
}
impl Default for FoldTextConfig {
fn default() -> Self {
Self {
fold_style: FoldStyle::Paper,
split_by: FoldSplit::Char,
hinge: FoldHinge::Top,
trigger: FoldTrigger::Mount,
stagger_from: FoldStaggerFrom::Start,
fold_angle: 92.0,
duration: 0.65,
stagger: 0.045,
ease: FoldEase::Power3Out,
perspective: 700.0,
crease_shading: 0.55,
loop_delay: 1.4,
hover_refold: false,
refold_radius: 140.0,
refold_angle: 45.0,
font_size: 80.0,
font_weight: 800,
letter_spacing: -2.0,
font_family: Typography::display_family().into(),
color: None,
}
}
}
impl FoldTextConfig {
fn piece_duration(&self) -> f64 {
self.duration.max(0.08)
}
pub fn unfold_span(&self, count: usize) -> f64 {
self.piece_duration() + self.stagger.max(0.0) * count.saturating_sub(1) as f64
}
pub fn cycle_span(&self, count: usize) -> f64 {
let unfold = self.unfold_span(count);
let fold =
self.piece_duration() * 0.75 + self.stagger.max(0.0) * count.saturating_sub(1) as f64;
unfold + self.loop_delay.max(0.0) + fold
}
fn safe_angle(&self) -> f32 {
if self.fold_style == FoldStyle::Flip {
180.0
} else {
self.fold_angle.clamp(0.0, 180.0)
}
}
fn piece_progress(&self, elapsed: f64, rank: usize, reduced: bool) -> f32 {
if reduced {
return 1.0;
}
let local = (elapsed - self.stagger.max(0.0) * rank as f64) / self.piece_duration();
self.ease.sample(local as f32)
}
fn piece_fold(&self, elapsed: f64, rank: usize, count: usize, reduced: bool) -> f32 {
if reduced || self.trigger != FoldTrigger::Loop {
return 0.0;
}
let unfold = self.unfold_span(count);
let fold = self.piece_duration() * 0.75;
let local =
(elapsed - unfold - self.loop_delay.max(0.0) - self.stagger.max(0.0) * rank as f64)
/ fold;
FoldEase::Power2Out.sample(local as f32)
}
pub fn stagger_rank(&self, index: usize, count: usize) -> usize {
let last = count.saturating_sub(1);
match self.stagger_from {
FoldStaggerFrom::Start => index,
FoldStaggerFrom::End => last.saturating_sub(index),
FoldStaggerFrom::Center => {
let mid = last as f32 / 2.0;
((index as f32 - mid).abs().round() as usize).min(last)
}
FoldStaggerFrom::Edges => {
let mid = last as f32 / 2.0;
(mid - (index as f32 - mid).abs()).round().max(0.0) as usize
}
FoldStaggerFrom::Random => {
let mut seed = (index as u32).wrapping_mul(2_654_435_761) ^ 0x9E37_79B9;
seed ^= seed >> 15;
seed = seed.wrapping_mul(2_246_822_519);
seed ^= seed >> 13;
(seed as usize) % count.max(1)
}
}
}
}
#[derive(Clone, Copy, Debug)]
struct Bbox {
left: f32,
top: f32,
right: f32,
bottom: f32,
}
impl Bbox {
fn width(self) -> f32 {
(self.right - self.left).max(0.001)
}
fn height(self) -> f32 {
(self.bottom - self.top).max(0.001)
}
fn center(self) -> (f32, f32) {
(
(self.left + self.right) / 2.0,
(self.top + self.bottom) / 2.0,
)
}
}
#[derive(Clone, Debug)]
struct Glyph {
contours: Vec<PolylinePath>,
}
#[derive(Clone, Debug)]
struct Piece {
glyphs: Vec<Glyph>,
bbox: Bbox,
}
#[derive(Clone, Debug)]
struct Layout {
pieces: Vec<Piece>,
bbox: Bbox,
}
type LayoutResult = Result<Arc<Layout>, String>;
static LAYOUTS: OnceLock<Mutex<HashMap<String, Arc<Layout>>>> = OnceLock::new();
fn layout_key(text: &str, config: &FoldTextConfig) -> String {
format!(
"{}|{:?}|{:?}|{}|{}|{}",
text,
config.split_by,
config.fold_style,
config.font_family,
config.font_weight,
config.font_size
)
}
fn cached_layout(text: &str, config: &FoldTextConfig) -> LayoutResult {
let key = layout_key(text, config);
let cache = LAYOUTS.get_or_init(Default::default);
if let Some(hit) = cache
.lock()
.map_err(|_| "字形缓存不可用")?
.get(&key)
.cloned()
{
return Ok(hit);
}
let built = build_layout(text, config)?;
let mut cache = cache.lock().map_err(|_| "字形缓存不可用")?;
if cache.len() >= 32 {
cache.clear();
}
cache.insert(key, built.clone());
Ok(built)
}
fn build_layout(text: &str, config: &FoldTextConfig) -> LayoutResult {
let scale = config.font_size.clamp(8.0, 512.0);
let metrics = with_face(&config.font_family, config.font_weight, |face| {
let unit = scale / face.units_per_em() as f32;
let line_height = scale * 1.12;
let space = face
.glyph_index(' ')
.and_then(|id| face.glyph_hor_advance(id))
.unwrap_or(face.units_per_em() / 3) as f32
* unit;
let mut pieces = Vec::new();
let mut lines = 0usize;
let mut union = Bbox {
left: f32::MAX,
top: f32::MAX,
right: f32::MIN,
bottom: f32::MIN,
};
for (line_index, line) in text.split('\n').enumerate() {
lines = line_index + 1;
let mut pen_x = 0.0f32;
let line_top = line_index as f32 * line_height;
match config.split_by {
FoldSplit::Char => {
for ch in line.chars() {
if ch.is_whitespace() {
pen_x += space + config.letter_spacing;
continue;
}
let id = face
.glyph_index(ch)
.ok_or_else(|| format!("当前字体不包含字符:{ch}"))?;
let mut outline = Outline::glyph(face, id);
let ink = scale_outline(&mut outline, unit, pen_x, line_top);
let advance = face.glyph_hor_advance(id).unwrap_or(0) as f32 * unit;
let bbox = ink.unwrap_or(Bbox {
left: pen_x,
top: line_top,
right: pen_x + advance,
bottom: line_top + scale,
});
union = union_or(union, bbox);
pieces.push(Piece {
glyphs: vec![Glyph {
contours: outline.contours,
}],
bbox,
});
pen_x += advance + config.letter_spacing;
}
}
FoldSplit::Word | FoldSplit::Line => {
let groups: Vec<&str> = if config.split_by == FoldSplit::Line {
vec![line]
} else {
line.split_whitespace().collect()
};
for (group_index, group) in groups.into_iter().enumerate() {
if group.is_empty() {
continue;
}
if group_index > 0 {
pen_x += space + config.letter_spacing;
}
let mut glyphs = Vec::new();
let mut ink: Option<Bbox> = None;
for ch in group.chars() {
if ch.is_whitespace() {
pen_x += space + config.letter_spacing;
continue;
}
let id = face
.glyph_index(ch)
.ok_or_else(|| format!("当前字体不包含字符:{ch}"))?;
let mut outline = Outline::glyph(face, id);
if let Some(b) = scale_outline(&mut outline, unit, pen_x, line_top) {
ink = Some(match ink {
Some(prev) => union_or(prev, b),
None => b,
});
}
glyphs.push(Glyph {
contours: outline.contours,
});
let advance = face.glyph_hor_advance(id).unwrap_or(0) as f32 * unit;
pen_x += advance + config.letter_spacing;
}
if let Some(bbox) = ink {
union = union_or(union, bbox);
pieces.push(Piece { glyphs, bbox });
}
}
}
}
}
Ok((pieces, lines, union))
})?;
let (mut pieces, lines, union) = metrics;
if pieces.is_empty() {
return Err("没有可折叠的文字".to_string());
}
let bbox = if union.left == f32::MAX {
Bbox {
left: 0.0,
top: 0.0,
right: scale,
bottom: scale,
}
} else {
union
};
for piece in &mut pieces {
for glyph in &mut piece.glyphs {
for contour in &mut glyph.contours {
for p in &mut contour.points {
p.y -= bbox.top;
}
}
}
piece.bbox.top -= bbox.top;
piece.bbox.bottom -= bbox.top;
}
let _ = lines;
Ok(Arc::new(Layout {
pieces,
bbox: Bbox {
left: bbox.left,
top: 0.0,
right: bbox.right,
bottom: bbox.bottom - bbox.top,
},
}))
}
fn union_or(a: Bbox, b: Bbox) -> Bbox {
Bbox {
left: a.left.min(b.left),
top: a.top.min(b.top),
right: a.right.max(b.right),
bottom: a.bottom.max(b.bottom),
}
}
fn scale_outline(outline: &mut Outline, unit: f32, pen_x: f32, line_top: f32) -> Option<Bbox> {
if outline.contours.is_empty() {
return None;
}
let mut bbox = Bbox {
left: f32::MAX,
top: f32::MAX,
right: f32::MIN,
bottom: f32::MIN,
};
for contour in &mut outline.contours {
for p in &mut contour.points {
p.x = p.x * unit + pen_x;
p.y = p.y * unit + line_top;
bbox.left = bbox.left.min(p.x);
bbox.top = bbox.top.min(p.y);
bbox.right = bbox.right.max(p.x);
bbox.bottom = bbox.bottom.max(p.y);
}
}
(bbox.left != f32::MAX).then_some(bbox)
}
pub fn prepare_fold_text(text: &str, config: &FoldTextConfig) -> Result<(), String> {
cached_layout(text, config).map(|_| ())
}
struct State {
key: String,
generation: u64,
geometry: Option<LayoutResult>,
started: Option<f64>,
visible: bool,
hovered: bool,
replay: u64,
pointer: Option<(f32, f32)>,
refold: Vec<f32>,
aim: Vec<f32>,
last_frame: f64,
centers: Vec<(f32, f32)>,
}
impl State {
fn new() -> Self {
Self {
key: String::new(),
generation: 0,
geometry: None,
started: None,
visible: false,
hovered: false,
replay: 0,
pointer: None,
refold: Vec::new(),
aim: Vec::new(),
last_frame: 0.0,
centers: Vec::new(),
}
}
}
struct Panel<'a> {
glyphs: &'a [Glyph],
bbox: Bbox,
hinge: (f32, f32),
origin: (f32, f32),
angle: f32,
opacity: f32,
crease: f32,
slat: Option<Slat>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Slat {
Upper,
Lower,
}
#[derive(IntoElement)]
pub struct FoldText {
id: ElementId,
text: SharedString,
config: FoldTextConfig,
replay: u64,
elapsed: Option<f64>,
}
impl FoldText {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
config: FoldTextConfig::default(),
replay: 0,
elapsed: None,
}
}
pub fn config(mut self, config: FoldTextConfig) -> Self {
self.config = config;
self
}
pub fn replay(mut self, revision: u64) -> Self {
self.replay = revision;
self
}
pub fn elapsed(mut self, seconds: f64) -> Self {
self.elapsed = Some(seconds.max(0.0));
self
}
}
impl RenderOnce for FoldText {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let now = motion_now(cx);
let reduced = is_reduced_motion(cx);
let foreground = cx.arc_theme().colors.foreground;
let state = window.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "fold-state".into()),
cx,
|_, _| Rc::new(RefCell::new(State::new())),
);
let state = state.read(cx).clone();
let key = layout_key(&self.text, &self.config);
let changed = state.borrow().key != key;
if changed {
let mut s = state.borrow_mut();
s.key = key;
s.generation += 1;
s.geometry = None;
s.started = None;
s.refold.clear();
s.aim.clear();
s.centers.clear();
let generation = s.generation;
drop(s);
let target = state.clone();
let text = self.text.to_string();
let config = self.config.clone();
let task = cx
.background_executor()
.spawn(async move { cached_layout(&text, &config) });
window
.spawn(cx, async move |cx| {
let result = task.await;
let _ = cx.update(|window, _| {
let mut s = target.borrow_mut();
if s.generation == generation {
s.geometry = Some(result);
s.started = None;
window.refresh();
}
});
})
.detach();
}
let mut s = state.borrow_mut();
if s.replay != self.replay {
s.replay = self.replay;
s.started = Some(now);
}
let ready = s.geometry.as_ref().is_some_and(|r| r.is_ok());
let piece_count = s
.geometry
.as_ref()
.and_then(|r| r.as_ref().ok())
.map(|l| l.pieces.len())
.unwrap_or(0);
let starts_on_its_own =
matches!(self.config.trigger, FoldTrigger::Mount | FoldTrigger::Loop)
|| (self.config.trigger == FoldTrigger::Scroll && s.visible);
if ready && s.started.is_none() && starts_on_its_own {
s.started = Some(now);
}
if s.refold.len() != piece_count {
s.refold = vec![0.0; piece_count];
s.aim = vec![0.0; piece_count];
}
let cycle = self.config.cycle_span(piece_count);
let elapsed = self.elapsed.unwrap_or_else(|| {
s.started.map_or(
if self.config.trigger == FoldTrigger::Hover {
cycle.max(self.config.unfold_span(piece_count))
} else {
0.0
},
|start| now - start,
)
});
let looping =
self.config.trigger == FoldTrigger::Loop && self.elapsed.is_none() && !reduced;
let phase = if looping {
elapsed.rem_euclid(cycle.max(0.1))
} else {
elapsed
};
let animating = self.elapsed.is_none()
&& !reduced
&& s.visible
&& ready
&& s.started.is_some()
&& (looping || elapsed < self.config.unfold_span(piece_count) + 0.05);
drop(s);
if animating {
window.request_animation_frame();
}
let paint_state = state.clone();
let hover_state = state.clone();
let move_state = state.clone();
let config = self.config.clone();
let color = self.config.color.unwrap_or(foreground);
let height = {
let line_count = self.text.chars().filter(|c| *c == '\n').count() as f32 + 1.0;
self.config.font_size.clamp(8.0, 512.0) * 1.12 * line_count + 24.0
};
div()
.id(self.id)
.test_support()
.role(Role::Image)
.aria_label(self.text.clone())
.relative()
.w_full()
.min_w_0()
.h(px(height))
.on_hover(move |hovered, window, cx| {
let mut s = hover_state.borrow_mut();
let was = s.hovered;
s.hovered = *hovered;
if !*hovered {
s.pointer = None;
for aim in &mut s.aim {
*aim = 0.0;
}
}
if was != *hovered {
window.refresh();
}
let _ = cx;
})
.on_mouse_move(move |event: &MouseMoveEvent, window, _| {
let mut s = move_state.borrow_mut();
s.pointer = Some((f32::from(event.position.x), f32::from(event.position.y)));
window.refresh();
})
.child(
canvas(
move |bounds, window, _| {
let visible = !bounds.intersect(&window.content_mask().bounds).is_empty();
let mut s = paint_state.borrow_mut();
if s.visible != visible {
s.visible = visible;
window.request_animation_frame();
}
bounds
},
move |bounds, _, window, cx| {
let geometry = state.borrow().geometry.clone();
let Some(Ok(layout)) = geometry else { return };
paint_layout(
&layout,
&config,
phase,
reduced,
color,
bounds,
motion_now(cx),
&state,
window,
);
},
)
.size_full(),
)
}
}
#[allow(clippy::too_many_arguments)]
fn paint_layout(
layout: &Layout,
config: &FoldTextConfig,
elapsed: f64,
reduced: bool,
color: Hsla,
bounds: Bounds<Pixels>,
now: f64,
state: &Rc<RefCell<State>>,
window: &mut Window,
) {
let count = layout.pieces.len();
let box_w = f32::from(bounds.size.width);
let box_h = f32::from(bounds.size.height);
let fit = (box_w - 24.0) / layout.bbox.width().max(1.0);
let fit_h = (box_h - 24.0) / layout.bbox.height().max(1.0);
let scale = fit.min(fit_h).clamp(0.01, 1.0);
let offset_x = f32::from(bounds.origin.x) + (box_w - layout.bbox.width() * scale) / 2.0
- layout.bbox.left * scale;
let offset_y = f32::from(bounds.origin.y) + (box_h - layout.bbox.height() * scale) / 2.0;
let to_screen = |x: f32, y: f32| (offset_x + x * scale, offset_y + y * scale);
let perspective = config.perspective.clamp(120.0, 4000.0);
let axis_x = matches!(config.hinge, FoldHinge::Top | FoldHinge::Bottom);
let reduced_angle = reduced;
let mut need_more_frames = false;
{
let mut s = state.borrow_mut();
if s.centers.len() != count {
s.centers = vec![(0.0, 0.0); count];
}
for (index, piece) in layout.pieces.iter().enumerate() {
let (cx, cy) = piece.bbox.center();
let (sx, sy) = to_screen(cx, cy);
s.centers[index] = (sx, sy);
}
let pointer = s.pointer;
let radius = config.refold_radius.max(1.0);
let want = config.hover_refold && !reduced && pointer.is_some();
for index in 0..count {
let mut target = 0.0;
if want && let Some((px, py)) = pointer {
let (cx, cy) = s.centers[index];
let distance = ((cx - px).powi(2) + (cy - py).powi(2)).sqrt() / radius;
if distance < 1.0 {
target = 1.0 - distance * distance * (3.0 - 2.0 * distance);
}
}
s.aim[index] = target;
}
let dt = (now - s.last_frame).clamp(0.0, 0.064) as f32;
s.last_frame = now;
for index in 0..count {
let aim = s.aim[index];
let current = s.refold[index];
let rate: f32 = if aim > current { 14.0 } else { 6.0 };
let next = current + (aim - current) * (1.0 - (-rate * dt).exp());
s.refold[index] = if (aim - next).abs() < 0.002 {
aim
} else {
next
};
if s.refold[index] != aim {
need_more_frames = true;
}
}
}
if need_more_frames {
window.request_animation_frame();
}
let refold_values = state.borrow().refold.clone();
let slat_delay = 0.24f64;
for (index, piece) in layout.pieces.iter().enumerate() {
let rank = config.stagger_rank(index, count);
let progress = config.piece_progress(elapsed, rank, reduced)
* (1.0 - config.piece_fold(elapsed, rank, count, reduced));
let tilt = refold_values.get(index).copied().unwrap_or(0.0) * config.refold_angle.max(0.0);
let crease_amount =
config.crease_shading.clamp(0.0, 1.0) * (1.0 - progress + tilt / 90.0).clamp(0.0, 1.0);
let opacity = progress.clamp(0.0, 1.0);
if opacity <= 0.004 {
continue;
}
let (ox, oy) = to_screen(piece.bbox.center().0, piece.bbox.center().1);
let anchor = if config.fold_style == FoldStyle::Flip {
piece.bbox.center()
} else {
hinge_point(piece.bbox, config.hinge)
};
let (hx, hy) = to_screen(anchor.0, anchor.1);
if config.fold_style == FoldStyle::Blinds {
for (slat_index, slat) in [Slat::Upper, Slat::Lower].into_iter().enumerate() {
let offset = slat_index as f64 * slat_delay;
let local = config.piece_progress(elapsed - offset, rank, reduced)
* (1.0 - config.piece_fold(elapsed - offset, rank, count, reduced));
let slat_opacity = local.clamp(0.0, 1.0);
if slat_opacity <= 0.004 {
continue;
}
let (shx, shy) = slat_hinge(piece.bbox, slat, config.hinge);
let (shx, shy) = to_screen(shx, shy);
let panel = Panel {
glyphs: &piece.glyphs,
bbox: piece.bbox,
hinge: (shx, shy),
origin: (ox, oy),
angle: (1.0 - local) * config.safe_angle() + tilt,
opacity: slat_opacity,
crease: crease_amount,
slat: Some(slat),
};
draw_panel(
&panel,
config,
axis_x,
perspective,
scale,
to_screen,
color,
window,
);
}
continue;
}
let lift = if config.fold_style == FoldStyle::Flip && !reduced_angle {
config.font_size
* scale
* 0.45
* (std::f32::consts::PI * progress.clamp(0.0, 1.0)).sin()
} else {
0.0
};
let panel = Panel {
glyphs: &piece.glyphs,
bbox: piece.bbox,
hinge: (hx, hy),
origin: (ox, oy),
angle: (1.0 - progress) * config.safe_angle() + tilt,
opacity,
crease: crease_amount,
slat: None,
};
draw_panel_with_lift(
&panel,
config,
axis_x,
perspective,
scale,
to_screen,
lift,
color,
window,
);
}
}
fn hinge_point(bbox: Bbox, hinge: FoldHinge) -> (f32, f32) {
match hinge {
FoldHinge::Top => (bbox.center().0, bbox.top),
FoldHinge::Bottom => (bbox.center().0, bbox.bottom),
FoldHinge::Left => (bbox.left, bbox.center().1),
FoldHinge::Right => (bbox.right, bbox.center().1),
}
}
fn slat_hinge(bbox: Bbox, slat: Slat, hinge: FoldHinge) -> (f32, f32) {
let (cx, cy) = bbox.center();
let quarter = match slat {
Slat::Upper => 0.25,
Slat::Lower => 0.75,
};
match hinge {
FoldHinge::Top | FoldHinge::Bottom => (cx, bbox.top + bbox.height() * quarter),
FoldHinge::Left | FoldHinge::Right => (bbox.left + bbox.width() * quarter, cy),
}
}
#[allow(clippy::too_many_arguments)]
fn draw_panel(
panel: &Panel<'_>,
config: &FoldTextConfig,
axis_x: bool,
perspective: f32,
scale: f32,
to_screen: impl Fn(f32, f32) -> (f32, f32),
color: Hsla,
window: &mut Window,
) {
draw_panel_with_lift(
panel,
config,
axis_x,
perspective,
scale,
to_screen,
0.0,
color,
window,
);
}
#[allow(clippy::too_many_arguments)]
fn draw_panel_with_lift(
panel: &Panel<'_>,
_config: &FoldTextConfig,
axis_x: bool,
perspective: f32,
scale: f32,
to_screen: impl Fn(f32, f32) -> (f32, f32),
lift: f32,
color: Hsla,
window: &mut Window,
) {
let theta = panel.angle.to_radians();
let (sin, cos) = (theta.sin(), theta.cos());
let (hx, hy) = panel.hinge;
let (ox, oy) = panel.origin;
let project = |x: f32, y: f32| -> (f32, f32) {
let (sx, sy) = to_screen(x, y);
let (rx, ry, depth) = if axis_x {
let dy = sy - hy;
(sx, hy + dy * cos, dy * sin)
} else {
let dx = sx - hx;
(hx + dx * cos, sy, dx * sin)
};
let depth = depth - lift;
let k = perspective / (perspective + depth).max(1.0);
(ox + (rx - ox) * k, oy + (ry - oy) * k)
};
let mut fill = PathBuilder::fill();
let mut any = false;
for glyph in panel.glyphs {
for contour in &glyph.contours {
let points: Vec<PathPoint> = match panel.slat {
None => contour.points.clone(),
Some(slat) => clip_half(contour.points.as_slice(), panel.bbox, slat, axis_x),
};
if points.len() < 3 {
continue;
}
let first = project(points[0].x, points[0].y);
fill.move_to(point(px(first.0), px(first.1)));
for p in &points[1..] {
let (x, y) = project(p.x, p.y);
fill.line_to(point(px(x), px(y)));
}
fill.close();
any = true;
}
}
if !any {
return;
}
let Ok(path) = fill.build() else { return };
let mut ink = color;
ink.a *= panel.opacity;
window.paint_path(path.clone(), ink);
if panel.crease > 0.01 && panel.opacity > 0.05 {
let shade = panel.crease * panel.opacity;
const BANDS: usize = 8;
for band in 0..BANDS {
let from = band as f32 / BANDS as f32;
let span = 1.0 / BANDS as f32;
let alpha = shade * 0.58 * (1.0 - from).powf(1.4);
if alpha <= 0.008 {
continue;
}
let Some(rect) = band_mask(panel.bbox, from, span, axis_x, &project) else {
continue;
};
let dark = Hsla {
h: 0.0,
s: 0.0,
l: 0.0,
a: alpha.min(0.75),
};
window.with_content_mask(Some(ContentMask { bounds: rect }), |window| {
window.paint_path(path.clone(), dark);
});
}
if let Some(rect) = band_mask(panel.bbox, 0.86, 0.14, axis_x, &project) {
let highlight = Hsla {
h: 0.0,
s: 0.0,
l: 1.0,
a: (shade * 0.22).min(0.22),
};
window.with_content_mask(Some(ContentMask { bounds: rect }), |window| {
window.paint_path(path.clone(), highlight);
});
}
}
let _ = scale;
}
fn clip_half(points: &[PathPoint], bbox: Bbox, slat: Slat, axis_x: bool) -> Vec<PathPoint> {
const OVERLAP: f32 = 0.04;
if axis_x {
let mid = bbox.top + bbox.height() * (0.5 + OVERLAP);
let low = bbox.top + bbox.height() * (0.5 - OVERLAP);
match slat {
Slat::Upper => clip_polygon(points, mid, true, false),
Slat::Lower => clip_polygon(points, low, false, false),
}
} else {
let mid = bbox.left + bbox.width() * (0.5 + OVERLAP);
let low = bbox.left + bbox.width() * (0.5 - OVERLAP);
match slat {
Slat::Upper => clip_polygon(points, mid, true, true),
Slat::Lower => clip_polygon(points, low, false, true),
}
}
}
fn clip_polygon(points: &[PathPoint], at: f32, keep_less: bool, on_x: bool) -> Vec<PathPoint> {
if points.is_empty() {
return Vec::new();
}
let coord = |p: &PathPoint| if on_x { p.x } else { p.y };
let inside = |p: &PathPoint| {
if keep_less {
coord(p) <= at
} else {
coord(p) >= at
}
};
let mut out: Vec<PathPoint> = Vec::with_capacity(points.len() + 2);
for index in 0..points.len() {
let current = points[index];
let previous = points[(index + points.len() - 1) % points.len()];
let current_in = inside(¤t);
let previous_in = inside(&previous);
if current_in != previous_in {
let c0 = coord(&previous);
let c1 = coord(¤t);
let t = if (c1 - c0).abs() < f32::EPSILON {
0.0
} else {
(at - c0) / (c1 - c0)
};
let cut = PathPoint::new(
previous.x + (current.x - previous.x) * t,
previous.y + (current.y - previous.y) * t,
);
out.push(cut);
}
if current_in {
out.push(current);
}
}
out
}
fn band_mask(
bbox: Bbox,
from: f32,
span: f32,
axis_x: bool,
project: &impl Fn(f32, f32) -> (f32, f32),
) -> Option<Bounds<Pixels>> {
let (y0, y1) = if axis_x {
(
bbox.top + bbox.height() * from,
bbox.top + bbox.height() * (from + span),
)
} else {
(bbox.top, bbox.bottom)
};
let (x0, x1) = if axis_x {
(bbox.left, bbox.right)
} else {
(
bbox.left + bbox.width() * from,
bbox.left + bbox.width() * (from + span),
)
};
let corners = [(x0, y0), (x1, y0), (x0, y1), (x1, y1)];
let mut min_x = f32::MAX;
let mut min_y = f32::MAX;
let mut max_x = f32::MIN;
let mut max_y = f32::MIN;
for (x, y) in corners {
let (px_, py_) = project(x, y);
min_x = min_x.min(px_);
min_y = min_y.min(py_);
max_x = max_x.max(px_);
max_y = max_y.max(py_);
}
if min_x == f32::MAX {
return None;
}
let pad = 0.0;
Some(Bounds::new(
point(px(min_x - pad), px(min_y - pad)),
size(
px((max_x - min_x) + pad * 2.0),
px((max_y - min_y) + pad * 2.0),
),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unfold_timeline_matches_reference() {
let config = FoldTextConfig::default();
assert_eq!(config.piece_progress(0.0, 0, false), 0.0);
assert_eq!(config.piece_progress(0.65, 0, false), 1.0);
assert!(config.piece_progress(0.10, 3, false) < 0.55);
assert!((config.unfold_span(4) - (0.65 + 0.135)).abs() < 1e-9);
assert_eq!(config.piece_progress(0.0, 0, true), 1.0);
}
#[test]
fn stagger_origins_pick_the_right_order() {
let mut config = FoldTextConfig::default();
assert_eq!(config.stagger_rank(0, 5), 0);
config.stagger_from = FoldStaggerFrom::End;
assert_eq!(config.stagger_rank(0, 5), 4);
config.stagger_from = FoldStaggerFrom::Center;
assert_eq!(config.stagger_rank(2, 5), 0);
assert_eq!(config.stagger_rank(0, 5), 2);
config.stagger_from = FoldStaggerFrom::Edges;
assert_eq!(config.stagger_rank(0, 5), 0);
assert_eq!(config.stagger_rank(2, 5), 2);
config.stagger_from = FoldStaggerFrom::Random;
let a: Vec<_> = (0..8).map(|i| config.stagger_rank(i, 8)).collect();
let b: Vec<_> = (0..8).map(|i| config.stagger_rank(i, 8)).collect();
assert_eq!(a, b);
assert!(a.iter().all(|rank| *rank < 8));
}
#[test]
fn layout_splits_by_grapheme_word_and_line() {
let config = FoldTextConfig::default();
let by_char = cached_layout("Arc", &config).unwrap();
assert_eq!(by_char.pieces.len(), 3);
let words = FoldTextConfig {
split_by: FoldSplit::Word,
..Default::default()
};
assert_eq!(cached_layout("Arc rs", &words).unwrap().pieces.len(), 2);
let lines = FoldTextConfig {
split_by: FoldSplit::Line,
..Default::default()
};
let two_lines = cached_layout("Arc\nrs", &lines).unwrap();
assert_eq!(two_lines.pieces.len(), 2);
assert!(two_lines.bbox.height() > config.font_size);
}
#[test]
fn every_piece_reports_its_own_ink_box() {
let layout = cached_layout("Fold", &FoldTextConfig::default()).unwrap();
for piece in &layout.pieces {
assert!(piece.bbox.width() > 0.5, "{:?}", piece.bbox);
assert!(piece.bbox.height() > 0.5, "{:?}", piece.bbox);
}
assert!(layout.pieces[0].bbox.left < layout.pieces[1].bbox.left);
}
#[test]
fn slat_clipping_splits_a_contour_in_two() {
let square = vec![
PathPoint::new(0.0, 0.0),
PathPoint::new(10.0, 0.0),
PathPoint::new(10.0, 10.0),
PathPoint::new(0.0, 10.0),
];
let upper = clip_polygon(&square, 5.0, true, false);
let lower = clip_polygon(&square, 5.0, false, false);
assert!(upper.iter().all(|p| p.y <= 5.0));
assert!(lower.iter().all(|p| p.y >= 5.0));
assert_eq!(upper.len(), 4);
assert_eq!(lower.len(), 4);
}
}