azul-css 0.0.8

Common datatypes used for styling applications using the Azul desktop GUI framework
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
//! CSS string parsing utilities: parenthesized expressions, quote stripping,
//! comma/whitespace-aware splitting that respects nesting depth, and CSS
//! image/url path parsing.

use crate::corety::AzString;

/// Splits a string by commas, but respects parentheses/braces
///
/// E.g. `url(something,else), url(another,thing)` becomes `["url(something,else)",
/// "url(another,thing)"]` whereas a normal split by comma would yield `["url(something", "else)",
/// "url(another", "thing)"]`
pub fn split_string_respect_comma(input: &str) -> Vec<&str> {
    split_string_by_char(input, ',')
}

/// Splits a string by whitespace, but respects parentheses/braces
///
/// E.g. `translateX(10px) rotate(90deg)` becomes `["translateX(10px)", "rotate(90deg)"]`
pub fn split_string_respect_whitespace(input: &str) -> Vec<&str> {
    let mut items = Vec::<&str>::new();
    let mut current_start = 0;
    let mut depth = 0;
    let input_bytes = input.as_bytes();

    for (idx, &ch) in input_bytes.iter().enumerate() {
        match ch {
            b'(' => depth += 1,
            b')' => depth -= 1,
            b' ' | b'\t' | b'\n' | b'\r' if depth == 0 => {
                if current_start < idx {
                    items.push(&input[current_start..idx]);
                }
                current_start = idx + 1;
            }
            _ => {}
        }
    }

    // Add the last segment
    if current_start < input.len() {
        items.push(&input[current_start..]);
    }

    items
}

fn split_string_by_char(input: &str, target_char: char) -> Vec<&str> {
    let mut comma_separated_items = Vec::<&str>::new();
    let mut current_input = input;

    'outer: loop {
        let (skip_next_braces_result, character_was_found) =
            match skip_next_braces(current_input, target_char) {
                Some(s) => s,
                None => break 'outer,
            };
        if character_was_found {
            comma_separated_items.push(&current_input[..skip_next_braces_result]);
            current_input = &current_input[(skip_next_braces_result + 1)..];
        } else {
            comma_separated_items.push(current_input);
            break 'outer;
        }
    }

    comma_separated_items
}

/// Given a string, returns how many characters need to be skipped
fn skip_next_braces(input: &str, target_char: char) -> Option<(usize, bool)> {
    let mut depth = 0;
    let mut last_character: Option<usize> = None;
    let mut character_was_found = false;

    if input.is_empty() {
        return None;
    }

    for (idx, ch) in input.char_indices() {
        last_character = Some(idx);
        match ch {
            '(' => {
                depth += 1;
            }
            ')' => {
                depth -= 1;
            }
            c => {
                if c == target_char && depth == 0 {
                    character_was_found = true;
                    break;
                }
            }
        }
    }

    last_character.map(|lc| (lc, character_was_found))
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
pub enum ParenthesisParseError<'a> {
    UnclosedBraces,
    NoOpeningBraceFound,
    NoClosingBraceFound,
    StopWordNotFound(&'a str),
    EmptyInput,
}

impl_display! { ParenthesisParseError<'a>, {
    UnclosedBraces => format!("Unclosed parenthesis"),
    NoOpeningBraceFound => format!("Expected value in parenthesis (missing \"(\")"),
    NoClosingBraceFound => format!("Missing closing parenthesis (missing \")\")"),
    StopWordNotFound(e) => format!("Stopword not found, found: \"{}\"", e),
    EmptyInput => format!("Empty parenthesis"),
}}

/// Owned version of ParenthesisParseError.
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum ParenthesisParseErrorOwned {
    UnclosedBraces,
    NoOpeningBraceFound,
    NoClosingBraceFound,
    StopWordNotFound(AzString),
    EmptyInput,
}

impl<'a> ParenthesisParseError<'a> {
    pub fn to_contained(&self) -> ParenthesisParseErrorOwned {
        match self {
            ParenthesisParseError::UnclosedBraces => ParenthesisParseErrorOwned::UnclosedBraces,
            ParenthesisParseError::NoOpeningBraceFound => {
                ParenthesisParseErrorOwned::NoOpeningBraceFound
            }
            ParenthesisParseError::NoClosingBraceFound => {
                ParenthesisParseErrorOwned::NoClosingBraceFound
            }
            ParenthesisParseError::StopWordNotFound(s) => {
                ParenthesisParseErrorOwned::StopWordNotFound(s.to_string().into())
            }
            ParenthesisParseError::EmptyInput => ParenthesisParseErrorOwned::EmptyInput,
        }
    }
}

impl ParenthesisParseErrorOwned {
    pub fn to_shared<'a>(&'a self) -> ParenthesisParseError<'a> {
        match self {
            ParenthesisParseErrorOwned::UnclosedBraces => ParenthesisParseError::UnclosedBraces,
            ParenthesisParseErrorOwned::NoOpeningBraceFound => {
                ParenthesisParseError::NoOpeningBraceFound
            }
            ParenthesisParseErrorOwned::NoClosingBraceFound => {
                ParenthesisParseError::NoClosingBraceFound
            }
            ParenthesisParseErrorOwned::StopWordNotFound(s) => {
                ParenthesisParseError::StopWordNotFound(s.as_str())
            }
            ParenthesisParseErrorOwned::EmptyInput => ParenthesisParseError::EmptyInput,
        }
    }
}

/// Checks whether a given input is enclosed in parentheses, prefixed
/// by a certain number of stopwords.
///
/// On success, returns what the stopword was + the string inside the braces
/// on failure returns None.
///
/// ```rust
/// # use azul_css::props::basic::parse::{parse_parentheses, ParenthesisParseError::*};
/// // Search for the nearest "abc()" brace
/// assert_eq!(
///     parse_parentheses("abc(def(g))", &["abc"]),
///     Ok(("abc", "def(g)"))
/// );
/// assert_eq!(
///     parse_parentheses("abc(def(g))", &["def"]),
///     Err(StopWordNotFound("abc"))
/// );
/// assert_eq!(
///     parse_parentheses("def(ghi(j))", &["def"]),
///     Ok(("def", "ghi(j)"))
/// );
/// assert_eq!(
///     parse_parentheses("abc(def(g))", &["abc", "def"]),
///     Ok(("abc", "def(g)"))
/// );
/// ```
pub fn parse_parentheses<'a>(
    input: &'a str,
    stopwords: &[&'static str],
) -> Result<(&'static str, &'a str), ParenthesisParseError<'a>> {
    use self::ParenthesisParseError::*;

    let input = input.trim();
    if input.is_empty() {
        return Err(EmptyInput);
    }

    let first_open_brace = input.find('(').ok_or(NoOpeningBraceFound)?;
    let found_stopword = &input[..first_open_brace];

    // CSS does not allow for space between the ( and the stopword, so no .trim() here
    let mut validated_stopword = None;
    for stopword in stopwords {
        if found_stopword == *stopword {
            validated_stopword = Some(stopword);
            break;
        }
    }

    let validated_stopword = validated_stopword.ok_or(StopWordNotFound(found_stopword))?;
    let last_closing_brace = input.rfind(')').ok_or(NoClosingBraceFound)?;

    Ok((
        validated_stopword,
        &input[(first_open_brace + 1)..last_closing_brace],
    ))
}

/// String has unbalanced `'` or `"` quotation marks
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct UnclosedQuotesError<'a>(pub &'a str);

impl<'a> From<UnclosedQuotesError<'a>> for CssImageParseError<'a> {
    fn from(err: UnclosedQuotesError<'a>) -> Self {
        CssImageParseError::UnclosedQuotes(err.0)
    }
}

/// A string that has been stripped of the beginning and ending quote
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct QuoteStripped<'a>(pub &'a str);

/// Strip quotes from an input, given that both quotes use either `"` or `'`, but not both.
///
/// # Example
///
/// ```rust
/// # extern crate azul_css;
/// # use azul_css::props::basic::parse::{strip_quotes, QuoteStripped, UnclosedQuotesError};
/// assert_eq!(
///     strip_quotes("\"Helvetica\""),
///     Ok(QuoteStripped("Helvetica"))
/// );
/// assert_eq!(strip_quotes("'Arial'"), Ok(QuoteStripped("Arial")));
/// assert_eq!(
///     strip_quotes("\"Arial'"),
///     Err(UnclosedQuotesError("\"Arial'"))
/// );
/// ```
pub fn strip_quotes<'a>(input: &'a str) -> Result<QuoteStripped<'a>, UnclosedQuotesError<'a>> {
    let mut double_quote_iter = input.splitn(2, '"');
    double_quote_iter.next();
    let mut single_quote_iter = input.splitn(2, '\'');
    single_quote_iter.next();

    let first_double_quote = double_quote_iter.next();
    let first_single_quote = single_quote_iter.next();
    if first_double_quote.is_some() && first_single_quote.is_some() {
        return Err(UnclosedQuotesError(input));
    }
    if let Some(quote_contents) = first_double_quote {
        if !quote_contents.ends_with('"') {
            return Err(UnclosedQuotesError(quote_contents));
        }
        Ok(QuoteStripped(quote_contents.trim_end_matches("\"")))
    } else if let Some(quote_contents) = first_single_quote {
        if !quote_contents.ends_with('\'') {
            return Err(UnclosedQuotesError(input));
        }
        Ok(QuoteStripped(quote_contents.trim_end_matches("'")))
    } else {
        Err(UnclosedQuotesError(input))
    }
}

#[derive(Copy, Clone, PartialEq)]
pub enum CssImageParseError<'a> {
    UnclosedQuotes(&'a str),
}

impl_debug_as_display!(CssImageParseError<'a>);
impl_display! {CssImageParseError<'a>, {
    UnclosedQuotes(e) => format!("Unclosed quotes: \"{}\"", e),
}}

/// Owned version of CssImageParseError.
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum CssImageParseErrorOwned {
    UnclosedQuotes(AzString),
}

impl<'a> CssImageParseError<'a> {
    /// Converts to the owned variant.
    pub fn to_contained(&self) -> CssImageParseErrorOwned {
        match self {
            CssImageParseError::UnclosedQuotes(s) => {
                CssImageParseErrorOwned::UnclosedQuotes(s.to_string().into())
            }
        }
    }
}

impl CssImageParseErrorOwned {
    /// Converts to the borrowed variant.
    pub fn to_shared<'a>(&'a self) -> CssImageParseError<'a> {
        match self {
            CssImageParseErrorOwned::UnclosedQuotes(s) => {
                CssImageParseError::UnclosedQuotes(s.as_str())
            }
        }
    }
}

/// A string slice that has been stripped of its quotes.
/// In CSS, quotes are optional in url() so we accept both quoted and unquoted strings.
pub fn parse_image<'a>(input: &'a str) -> Result<AzString, CssImageParseError<'a>> {
    Ok(match strip_quotes(input) {
        Ok(stripped) => stripped.0.into(),
        Err(_) => input.trim().into(),
    })
}

#[cfg(all(test, feature = "parser"))]
mod tests {
    use super::*;

    #[test]
    fn test_strip_quotes() {
        assert_eq!(strip_quotes("'hello'").unwrap(), QuoteStripped("hello"));
        assert_eq!(strip_quotes("\"world\"").unwrap(), QuoteStripped("world"));
        assert_eq!(
            strip_quotes("\"  spaced  \"").unwrap(),
            QuoteStripped("  spaced  ")
        );
        assert!(strip_quotes("'unclosed").is_err());
        assert!(strip_quotes("\"mismatched'").is_err());
        assert!(strip_quotes("no-quotes").is_err());
    }

    #[test]
    fn test_parse_parentheses() {
        assert_eq!(
            parse_parentheses("url(image.png)", &["url"]),
            Ok(("url", "image.png"))
        );
        assert_eq!(
            parse_parentheses("linear-gradient(red, blue)", &["linear-gradient"]),
            Ok(("linear-gradient", "red, blue"))
        );
        assert_eq!(
            parse_parentheses("var(--my-var, 10px)", &["var"]),
            Ok(("var", "--my-var, 10px"))
        );
        assert_eq!(
            parse_parentheses("  rgb( 255, 0, 0 )  ", &["rgb", "rgba"]),
            Ok(("rgb", " 255, 0, 0 "))
        );
    }

    #[test]
    fn test_parse_parentheses_errors() {
        // Stopword not found
        assert!(parse_parentheses("rgba(255,0,0,1)", &["rgb"]).is_err());
        // No opening brace
        assert!(parse_parentheses("url'image.png'", &["url"]).is_err());
        // No closing brace
        assert!(parse_parentheses("url(image.png", &["url"]).is_err());
    }

    #[test]
    fn test_split_string_respect_comma() {
        // Simple case
        let simple = "one, two, three";
        assert_eq!(
            split_string_respect_comma(simple),
            vec!["one", " two", " three"]
        );

        // With parentheses
        let with_parens = "rgba(255, 0, 0, 1), #ff00ff";
        assert_eq!(
            split_string_respect_comma(with_parens),
            vec!["rgba(255, 0, 0, 1)", " #ff00ff"]
        );

        // Multiple parentheses
        let multi_parens =
            "linear-gradient(to right, rgba(0,0,0,0), rgba(0,0,0,1)), url(image.png)";
        assert_eq!(
            split_string_respect_comma(multi_parens),
            vec![
                "linear-gradient(to right, rgba(0,0,0,0), rgba(0,0,0,1))",
                " url(image.png)"
            ]
        );

        // No commas
        let no_commas = "rgb(0,0,0)";
        assert_eq!(split_string_respect_comma(no_commas), vec!["rgb(0,0,0)"]);
    }
}