summaryrefslogtreecommitdiff
path: root/src/library/text.rs
blob: a0ffc56c806085aeb22006b404c0600297e380dd (plain) (blame)
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
use crate::exec::{FontState, LineState};
use crate::font::{FontStretch, FontStyle, FontWeight};
use crate::layout::Paint;

use super::*;

/// `font`: Configure the font.
pub fn font(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let families = args.all(ctx);
    let list = if families.is_empty() {
        args.named(ctx, "family")
    } else {
        Some(FontDef(families))
    };

    let size = args.eat(ctx).or_else(|| args.named::<Linear>(ctx, "size"));
    let style = args.named(ctx, "style");
    let weight = args.named(ctx, "weight");
    let stretch = args.named(ctx, "stretch");
    let top_edge = args.named(ctx, "top-edge");
    let bottom_edge = args.named(ctx, "bottom-edge");
    let fill = args.named(ctx, "fill");
    let serif = args.named(ctx, "serif");
    let sans_serif = args.named(ctx, "sans-serif");
    let monospace = args.named(ctx, "monospace");
    let body = args.expect::<TemplateValue>(ctx, "body").unwrap_or_default();

    Value::template(move |ctx| {
        let font = ctx.state.font_mut();

        if let Some(linear) = size {
            font.size = linear.resolve(font.size);
        }

        if let Some(FontDef(list)) = &list {
            font.families_mut().list = list.clone();
        }

        if let Some(style) = style {
            font.variant.style = style;
        }

        if let Some(weight) = weight {
            font.variant.weight = weight;
        }

        if let Some(stretch) = stretch {
            font.variant.stretch = stretch;
        }

        if let Some(top_edge) = top_edge {
            font.top_edge = top_edge;
        }

        if let Some(bottom_edge) = bottom_edge {
            font.bottom_edge = bottom_edge;
        }

        if let Some(fill) = fill {
            font.fill = Paint::Color(fill);
        }

        if let Some(FamilyDef(serif)) = &serif {
            font.families_mut().serif = serif.clone();
        }

        if let Some(FamilyDef(sans_serif)) = &sans_serif {
            font.families_mut().sans_serif = sans_serif.clone();
        }

        if let Some(FamilyDef(monospace)) = &monospace {
            font.families_mut().monospace = monospace.clone();
        }

        body.exec(ctx);
    })
}

#[derive(Debug)]
struct FontDef(Vec<FontFamily>);

castable! {
    FontDef: "font family or array of font families",
    Value::Str(string) => Self(vec![FontFamily::Named(string.to_lowercase())]),
    Value::Array(values) => Self(values
        .into_iter()
        .filter_map(|v| v.cast().ok())
        .collect()
    ),
    #(family: FontFamily) => Self(vec![family]),
}

#[derive(Debug)]
struct FamilyDef(Vec<String>);

castable! {
    FamilyDef: "string or array of strings",
    Value::Str(string) => Self(vec![string.to_lowercase()]),
    Value::Array(values) => Self(values
        .into_iter()
        .filter_map(|v| v.cast().ok())
        .map(|string: EcoString| string.to_lowercase())
        .collect()
    ),
}

castable! {
    FontFamily: "font family",
    Value::Str(string) => Self::Named(string.to_lowercase())
}

castable! {
    FontStyle: "font style",
}

castable! {
    FontWeight: "font weight",
    Value::Int(number) => {
        let [min, max] = [Self::THIN, Self::BLACK];
        let message = || format!(
            "should be between {} and {}",
            min.to_number(),
            max.to_number(),
        );

        return if number < i64::from(min.to_number()) {
            CastResult::Warn(min, message())
        } else if number > i64::from(max.to_number()) {
            CastResult::Warn(max, message())
        } else {
            CastResult::Ok(Self::from_number(number as u16))
        };
    },
}

castable! {
    FontStretch: "font stretch",
    Value::Relative(relative) => {
        let [min, max] = [Self::ULTRA_CONDENSED, Self::ULTRA_EXPANDED];
        let message = || format!(
            "should be between {} and {}",
            Relative::new(min.to_ratio() as f64),
            Relative::new(max.to_ratio() as f64),
        );

        let ratio = relative.get() as f32;
        let value = Self::from_ratio(ratio);

        return if ratio < min.to_ratio() || ratio > max.to_ratio() {
            CastResult::Warn(value, message())
        } else {
            CastResult::Ok(value)
        };
    },
}

castable! {
    VerticalFontMetric: "vertical font metric",
}

/// `par`: Configure paragraphs.
pub fn par(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let spacing = args.named(ctx, "spacing");
    let leading = args.named(ctx, "leading");
    let word_spacing = args.named(ctx, "word-spacing");
    let body = args.expect::<TemplateValue>(ctx, "body").unwrap_or_default();

    Value::template(move |ctx| {
        if let Some(spacing) = spacing {
            ctx.state.par.spacing = spacing;
        }

        if let Some(leading) = leading {
            ctx.state.par.leading = leading;
        }

        if let Some(word_spacing) = word_spacing {
            ctx.state.par.word_spacing = word_spacing;
        }

        ctx.parbreak();
        body.exec(ctx);
    })
}

/// `lang`: Configure the language.
pub fn lang(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let iso = args.eat::<EcoString>(ctx).map(|s| lang_dir(&s));
    let dir = match args.named::<Spanned<Dir>>(ctx, "dir") {
        Some(dir) if dir.v.axis() == SpecAxis::Horizontal => Some(dir.v),
        Some(dir) => {
            ctx.diag(error!(dir.span, "must be horizontal"));
            None
        }
        None => None,
    };
    let body = args.expect::<TemplateValue>(ctx, "body").unwrap_or_default();

    Value::template(move |ctx| {
        if let Some(dir) = dir.or(iso) {
            ctx.state.lang.dir = dir;
        }

        ctx.parbreak();
        body.exec(ctx);
    })
}

/// The default direction for the language identified by `iso`.
fn lang_dir(iso: &str) -> Dir {
    match iso.to_ascii_lowercase().as_str() {
        "ar" | "he" | "fa" | "ur" | "ps" | "yi" => Dir::RTL,
        "en" | "fr" | "de" => Dir::LTR,
        _ => Dir::LTR,
    }
}

/// `strike`: Enable striken-through text.
pub fn strike(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    line_impl(ctx, args, |font| &mut font.strikethrough)
}

/// `underline`: Enable underlined text.
pub fn underline(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    line_impl(ctx, args, |font| &mut font.underline)
}

/// `overline`: Add an overline above text.
pub fn overline(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    line_impl(ctx, args, |font| &mut font.overline)
}

fn line_impl(
    ctx: &mut EvalContext,
    args: &mut FuncArgs,
    substate: fn(&mut FontState) -> &mut Option<Rc<LineState>>,
) -> Value {
    let stroke = args.eat(ctx).or_else(|| args.named(ctx, "stroke"));
    let thickness = args.eat(ctx).or_else(|| args.named::<Linear>(ctx, "thickness"));
    let offset = args.named(ctx, "offset");
    let extent = args.named(ctx, "extent").unwrap_or_default();
    let body = args.expect::<TemplateValue>(ctx, "body").unwrap_or_default();

    // Suppress any existing strikethrough if strength is explicitly zero.
    let state = thickness.map_or(true, |s| !s.is_zero()).then(|| {
        Rc::new(LineState {
            stroke: stroke.map(Paint::Color),
            thickness,
            offset,
            extent,
        })
    });

    Value::template(move |ctx| {
        *substate(ctx.state.font_mut()) = state.clone();
        body.exec(ctx);
    })
}