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
406
407
408
//! CSS property types for direction (for gradients).

use alloc::string::String;
use core::{fmt, num::ParseFloatError};
use crate::corety::AzString;

use crate::props::{
    basic::{
        angle::{
            parse_angle_value, AngleValue, CssAngleValueParseError, CssAngleValueParseErrorOwned,
        },
        geometry::{LayoutPoint, LayoutRect},
    },
    formatter::PrintAsCssValue,
};

/// Corner or side of a rectangle, used to specify CSS gradient directions
/// (e.g. `to top right`).
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum DirectionCorner {
    Right,
    Left,
    Top,
    Bottom,
    TopRight,
    TopLeft,
    BottomRight,
    BottomLeft,
}

impl fmt::Display for DirectionCorner {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                DirectionCorner::Right => "right",
                DirectionCorner::Left => "left",
                DirectionCorner::Top => "top",
                DirectionCorner::Bottom => "bottom",
                DirectionCorner::TopRight => "top right",
                DirectionCorner::TopLeft => "top left",
                DirectionCorner::BottomRight => "bottom right",
                DirectionCorner::BottomLeft => "bottom left",
            }
        )
    }
}

impl PrintAsCssValue for DirectionCorner {
    fn print_as_css_value(&self) -> String {
        format!("{}", self)
    }
}

impl DirectionCorner {
    pub const fn opposite(&self) -> Self {
        use self::DirectionCorner::*;
        match *self {
            Right => Left,
            Left => Right,
            Top => Bottom,
            Bottom => Top,
            TopRight => BottomLeft,
            BottomLeft => TopRight,
            TopLeft => BottomRight,
            BottomRight => TopLeft,
        }
    }

    pub const fn combine(&self, other: &Self) -> Option<Self> {
        use self::DirectionCorner::*;
        match (*self, *other) {
            (Right, Top) | (Top, Right) => Some(TopRight),
            (Left, Top) | (Top, Left) => Some(TopLeft),
            (Right, Bottom) | (Bottom, Right) => Some(BottomRight),
            (Left, Bottom) | (Bottom, Left) => Some(BottomLeft),
            _ => None,
        }
    }

    pub const fn to_point(&self, rect: &LayoutRect) -> LayoutPoint {
        use self::DirectionCorner::*;
        match *self {
            Right => LayoutPoint {
                x: rect.size.width,
                y: rect.size.height / 2,
            },
            Left => LayoutPoint {
                x: 0,
                y: rect.size.height / 2,
            },
            Top => LayoutPoint {
                x: rect.size.width / 2,
                y: 0,
            },
            Bottom => LayoutPoint {
                x: rect.size.width / 2,
                y: rect.size.height,
            },
            TopRight => LayoutPoint {
                x: rect.size.width,
                y: 0,
            },
            TopLeft => LayoutPoint { x: 0, y: 0 },
            BottomRight => LayoutPoint {
                x: rect.size.width,
                y: rect.size.height,
            },
            BottomLeft => LayoutPoint {
                x: 0,
                y: rect.size.height,
            },
        }
    }
}

/// A pair of corners representing the start and end of a CSS gradient direction.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct DirectionCorners {
    /// The corner or side from which the gradient starts.
    pub dir_from: DirectionCorner,
    /// The corner or side at which the gradient ends.
    pub dir_to: DirectionCorner,
}

/// CSS direction (necessary for gradients). Can either be a fixed angle or
/// a direction ("to right" / "to left", etc.).
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum Direction {
    Angle(AngleValue),
    FromTo(DirectionCorners),
}

impl Default for Direction {
    fn default() -> Self {
        Direction::FromTo(DirectionCorners {
            dir_from: DirectionCorner::Top,
            dir_to: DirectionCorner::Bottom,
        })
    }
}

impl PrintAsCssValue for Direction {
    fn print_as_css_value(&self) -> String {
        match self {
            Direction::Angle(a) => format!("{}", a),
            Direction::FromTo(d) => format!("to {}", d.dir_to), // simplified "from X to Y"
        }
    }
}

impl Direction {
    pub fn to_points(&self, rect: &LayoutRect) -> (LayoutPoint, LayoutPoint) {
        match self {
            Direction::Angle(angle_value) => {
                // Convert the angle to start/end points on the rectangle.
                // TODO: does not handle negative angles or angles >= 360 correctly.
                let deg = -angle_value.to_degrees();
                let width_half = rect.size.width as f32 / 2.0;
                let height_half = rect.size.height as f32 / 2.0;
                let hypotenuse_len = libm::hypotf(width_half, height_half);
                let angle_to_corner = libm::atanf(height_half / width_half).to_degrees();
                let corner_angle = if deg < 90.0 {
                    90.0 - angle_to_corner
                } else if deg < 180.0 {
                    90.0 + angle_to_corner
                } else if deg < 270.0 {
                    270.0 - angle_to_corner
                } else {
                    270.0 + angle_to_corner
                };
                let angle_diff = corner_angle - deg;
                let line_length = libm::fabsf(hypotenuse_len * libm::cosf(angle_diff.to_radians()));
                let dx = libm::sinf(deg.to_radians()) * line_length;
                let dy = libm::cosf(deg.to_radians()) * line_length;
                (
                    LayoutPoint::new(
                        libm::roundf(width_half - dx) as isize,
                        libm::roundf(height_half + dy) as isize,
                    ),
                    LayoutPoint::new(
                        libm::roundf(width_half + dx) as isize,
                        libm::roundf(height_half - dy) as isize,
                    ),
                )
            }
            Direction::FromTo(ft) => (ft.dir_from.to_point(rect), ft.dir_to.to_point(rect)),
        }
    }
}

// -- Parser

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

impl_display! { CssDirectionCornerParseError<'a>, {
    InvalidDirection(val) => format!("Invalid direction: \"{}\"", val),
}}

#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum CssDirectionCornerParseErrorOwned {
    InvalidDirection(AzString),
}

impl<'a> CssDirectionCornerParseError<'a> {
    pub fn to_contained(&self) -> CssDirectionCornerParseErrorOwned {
        match self {
            CssDirectionCornerParseError::InvalidDirection(s) => {
                CssDirectionCornerParseErrorOwned::InvalidDirection(s.to_string().into())
            }
        }
    }
}

impl CssDirectionCornerParseErrorOwned {
    pub fn to_shared<'a>(&'a self) -> CssDirectionCornerParseError<'a> {
        match self {
            CssDirectionCornerParseErrorOwned::InvalidDirection(s) => {
                CssDirectionCornerParseError::InvalidDirection(s.as_str())
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum CssDirectionParseError<'a> {
    Error(&'a str),
    InvalidArguments(&'a str),
    ParseFloat(ParseFloatError),
    CornerError(CssDirectionCornerParseError<'a>),
    AngleError(CssAngleValueParseError<'a>),
}

impl_display! {CssDirectionParseError<'a>, {
    Error(e) => e,
    InvalidArguments(val) => format!("Invalid arguments: \"{}\"", val),
    ParseFloat(e) => format!("Invalid value: {}", e),
    CornerError(e) => format!("Invalid corner value: {}", e),
    AngleError(e) => format!("Invalid angle value: {}", e),
}}

impl<'a> From<ParseFloatError> for CssDirectionParseError<'a> {
    fn from(e: ParseFloatError) -> Self {
        CssDirectionParseError::ParseFloat(e)
    }
}
impl_from! { CssDirectionCornerParseError<'a>, CssDirectionParseError::CornerError }
impl_from! { CssAngleValueParseError<'a>, CssDirectionParseError::AngleError }

#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum CssDirectionParseErrorOwned {
    Error(AzString),
    InvalidArguments(AzString),
    ParseFloat(crate::props::basic::error::ParseFloatError),
    CornerError(CssDirectionCornerParseErrorOwned),
    AngleError(CssAngleValueParseErrorOwned),
}

impl<'a> CssDirectionParseError<'a> {
    pub fn to_contained(&self) -> CssDirectionParseErrorOwned {
        match self {
            CssDirectionParseError::Error(s) => CssDirectionParseErrorOwned::Error(s.to_string().into()),
            CssDirectionParseError::InvalidArguments(s) => {
                CssDirectionParseErrorOwned::InvalidArguments(s.to_string().into())
            }
            CssDirectionParseError::ParseFloat(e) => {
                CssDirectionParseErrorOwned::ParseFloat(e.clone().into())
            }
            CssDirectionParseError::CornerError(e) => {
                CssDirectionParseErrorOwned::CornerError(e.to_contained())
            }
            CssDirectionParseError::AngleError(e) => {
                CssDirectionParseErrorOwned::AngleError(e.to_contained())
            }
        }
    }
}

impl CssDirectionParseErrorOwned {
    pub fn to_shared<'a>(&'a self) -> CssDirectionParseError<'a> {
        match self {
            CssDirectionParseErrorOwned::Error(s) => CssDirectionParseError::Error(s.as_str()),
            CssDirectionParseErrorOwned::InvalidArguments(s) => {
                CssDirectionParseError::InvalidArguments(s.as_str())
            }
            CssDirectionParseErrorOwned::ParseFloat(e) => {
                CssDirectionParseError::ParseFloat(e.to_std())
            }
            CssDirectionParseErrorOwned::CornerError(e) => {
                CssDirectionParseError::CornerError(e.to_shared())
            }
            CssDirectionParseErrorOwned::AngleError(e) => {
                CssDirectionParseError::AngleError(e.to_shared())
            }
        }
    }
}

#[cfg(feature = "parser")]
fn parse_direction_corner<'a>(
    input: &'a str,
) -> Result<DirectionCorner, CssDirectionCornerParseError<'a>> {
    match input {
        "right" => Ok(DirectionCorner::Right),
        "left" => Ok(DirectionCorner::Left),
        "top" => Ok(DirectionCorner::Top),
        "bottom" => Ok(DirectionCorner::Bottom),
        _ => Err(CssDirectionCornerParseError::InvalidDirection(input)),
    }
}

#[cfg(feature = "parser")]
pub fn parse_direction<'a>(input: &'a str) -> Result<Direction, CssDirectionParseError<'a>> {
    let mut input_iter = input.split_whitespace();
    let first_input = input_iter
        .next()
        .ok_or(CssDirectionParseError::Error(input))?;

    if let Ok(angle) = parse_angle_value(first_input) {
        return Ok(Direction::Angle(angle));
    }

    if first_input != "to" {
        return Err(CssDirectionParseError::InvalidArguments(input));
    }

    let components = input_iter.collect::<Vec<_>>();
    if components.is_empty() || components.len() > 2 {
        return Err(CssDirectionParseError::InvalidArguments(input));
    }

    let first_corner = parse_direction_corner(components[0])?;
    let end = if components.len() == 2 {
        let second_corner = parse_direction_corner(components[1])?;
        first_corner
            .combine(&second_corner)
            .ok_or(CssDirectionParseError::InvalidArguments(input))?
    } else {
        first_corner
    };

    Ok(Direction::FromTo(DirectionCorners {
        dir_from: end.opposite(),
        dir_to: end,
    }))
}

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

    #[test]
    fn test_parse_direction_angle() {
        assert_eq!(
            parse_direction("45deg").unwrap(),
            Direction::Angle(AngleValue::deg(45.0))
        );
        assert_eq!(
            parse_direction("  -0.25turn  ").unwrap(),
            Direction::Angle(AngleValue::turn(-0.25))
        );
    }

    #[test]
    fn test_parse_direction_corners() {
        assert_eq!(
            parse_direction("to right").unwrap(),
            Direction::FromTo(DirectionCorners {
                dir_from: DirectionCorner::Left,
                dir_to: DirectionCorner::Right,
            })
        );
        assert_eq!(
            parse_direction("to top left").unwrap(),
            Direction::FromTo(DirectionCorners {
                dir_from: DirectionCorner::BottomRight,
                dir_to: DirectionCorner::TopLeft,
            })
        );
        assert_eq!(
            parse_direction("to left top").unwrap(),
            Direction::FromTo(DirectionCorners {
                dir_from: DirectionCorner::BottomRight,
                dir_to: DirectionCorner::TopLeft,
            })
        );
    }

    #[test]
    fn test_parse_direction_errors() {
        assert!(parse_direction("").is_err());
        assert!(parse_direction("to").is_err());
        assert!(parse_direction("right").is_err());
        assert!(parse_direction("to center").is_err());
        assert!(parse_direction("to top right bottom").is_err());
        assert!(parse_direction("to top top").is_err());
    }
}