aboutsummaryrefslogtreecommitdiffstats
path: root/components/style/values/specified/position.rs
blob: 6b0086b41ff00fde00cd7ba47ffc2965ef29518e (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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! CSS handling for the specified value of
//! [`position`][position]s
//!
//! [position]: https://drafts.csswg.org/css-backgrounds-3/#position

use cssparser::{Parser, ToCss, Token};
use std::fmt;
use values::HasViewportPercentage;
use values::computed::position as computed_position;
use values::computed::{CalcLengthOrPercentage, Context};
use values::computed::{LengthOrPercentage as ComputedLengthOrPercentage, ToComputedValue};
use values::specified::{LengthOrPercentage, Percentage};

#[derive(Debug, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Position {
    pub horiz_keyword: Option<Keyword>,
    pub horiz_position: Option<LengthOrPercentage>,
    pub vert_keyword: Option<Keyword>,
    pub vert_position: Option<LengthOrPercentage>,
}

impl ToCss for Position {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
        let mut space_at_last = false;
        if let Some(horiz_key) = self.horiz_keyword {
            try!(horiz_key.to_css(dest));
            try!(dest.write_str(" "));
            space_at_last = true;
        };
        if let Some(horiz_pos) = self.horiz_position {
            try!(horiz_pos.to_css(dest));
            try!(dest.write_str(" "));
            space_at_last = true;
        };
        if let Some(vert_key) = self.vert_keyword {
            try!(vert_key.to_css(dest));
            space_at_last = false;
        };
        if let Some(vert_pos) = self.vert_position {
            if space_at_last == false {
                try!(dest.write_str(" "));
            }
            try!(vert_pos.to_css(dest));
        };
        Ok(())
    }
}

impl HasViewportPercentage for Position {
    fn has_viewport_percentage(&self) -> bool {
        let horiz_viewport = if let Some(horiz_pos) = self.horiz_position {
            horiz_pos.has_viewport_percentage()
        } else {
            false
        };

        let vert_viewport = if let Some(vert_pos) = self.vert_position {
            vert_pos.has_viewport_percentage()
        } else {
            false
        };
        horiz_viewport || vert_viewport
    }
}

#[derive(Debug, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum Keyword {
    Center,
    Left,
    Right,
    Top,
    Bottom,
}

// http://dev.w3.org/csswg/css2/colors.html#propdef-background-position
#[derive(Clone, PartialEq, Copy)]
pub enum PositionComponent {
    Length(LengthOrPercentage),
    Keyword(Keyword),
}

impl Position {
    pub fn new(mut first_position: Option<PositionComponent>, mut second_position: Option<PositionComponent>,
               first_keyword: Option<PositionComponent>, second_keyword: Option<PositionComponent>)
            -> Result<Position, ()> {
        // Unwrap for checking if values are at right place.
        let first_key = first_keyword.unwrap_or(PositionComponent::Keyword(Keyword::Left));
        let second_key = second_keyword.unwrap_or(PositionComponent::Keyword(Keyword::Top));

        // Check if position specified after center keyword.
        if let PositionCategory::OtherKeyword = category(first_key) {
            if let Some(_) = first_position {
                return Err(());
            };
        };
        if let PositionCategory::OtherKeyword = category(second_key) {
            if let Some(_) = second_position {
                return Err(());
            };
        };

        // Check first and second keywords for both 2 and 4 value positions.
        let (horiz_keyword, vert_keyword) = match (category(first_key), category(second_key)) {
            // Don't allow two vertical keywords or two horizontal keywords.
            // also don't allow length/percentage values in the wrong position
            (PositionCategory::HorizontalKeyword, PositionCategory::HorizontalKeyword) |
            (PositionCategory::VerticalKeyword, PositionCategory::VerticalKeyword) |
            (PositionCategory::LengthOrPercentage, PositionCategory::HorizontalKeyword) |
            (PositionCategory::VerticalKeyword, PositionCategory::LengthOrPercentage) => return Err(()),

            // Swap if both are keywords and vertical precedes horizontal.
            (PositionCategory::VerticalKeyword, PositionCategory::HorizontalKeyword) |
            (PositionCategory::VerticalKeyword, PositionCategory::OtherKeyword) |
            (PositionCategory::OtherKeyword, PositionCategory::HorizontalKeyword) => {
                let tmp = first_position;
                first_position = second_position;
                second_position = tmp;

                (second_keyword, first_keyword)
            },
            // By default, horizontal is first.
            _ => (first_keyword, second_keyword),
        };

        // Unwrap positions from PositionComponent and wrap with Option
        let (first_position, second_position) = if let Some(PositionComponent::Length(horiz_pos)) = first_position {
            if let Some(PositionComponent::Length(vert_pos)) = second_position {
                (Some(horiz_pos), Some(vert_pos))
            } else {
                (Some(horiz_pos), None)
            }
        } else {
            if let Some(PositionComponent::Length(vert_pos)) = second_position {
                (None, Some(vert_pos))
            } else {
                (None, None)
            }
        };

        // Unwrap keywords from PositionComponent and wrap with Option.
        let (horizontal_keyword, vertical_keyword) = if let Some(PositionComponent::Keyword(horiz_key)) =
                                                     horiz_keyword {
            if let Some(PositionComponent::Keyword(vert_key)) = vert_keyword {
                (Some(horiz_key), Some(vert_key))
            } else {
                (Some(horiz_key), None)
            }
        } else {
            if let Some(PositionComponent::Keyword(vert_key)) = vert_keyword {
                (None, Some(vert_key))
            } else {
                (None, None)
            }
        };

        Ok(Position {
            horiz_keyword: horizontal_keyword,
            horiz_position: first_position,
            vert_keyword: vertical_keyword,
            vert_position: second_position,
        })
    }

    pub fn parse(input: &mut Parser) -> Result<Position, ()> {
        let first = try!(PositionComponent::parse(input));
        let second = input.try(PositionComponent::parse)
            .unwrap_or(PositionComponent::Keyword(Keyword::Center));

        // Try to parse third and fourth values
        if let Ok(third) = input.try(PositionComponent::parse) {
            if let Ok(fourth) = input.try(PositionComponent::parse) {
                // Handle 4 value background position
                Position::new(Some(second), Some(fourth), Some(first), Some(third))
            } else {
                // Handle 3 value background position there are several options:
                if let PositionCategory::LengthOrPercentage = category(first) {
                    // "length keyword length"
                    Position::new(Some(first), Some(third), None, Some(second))
                } else {
                    if let PositionCategory::LengthOrPercentage = category(second) {
                        if let PositionCategory::LengthOrPercentage = category(third) {
                            // "keyword length length"
                            Position::new(Some(second), Some(third), Some(first), None)
                        } else {
                            // "keyword length keyword"
                            Position::new(Some(second), None, Some(first), Some(third))
                        }
                    } else {
                        // "keyword keyword length"
                        Position::new(None, Some(third), Some(first), Some(second))
                    }
                }
            }
        } else {
            // Handle 2 value background position.
            if let PositionCategory::LengthOrPercentage = category(first) {
                if let PositionCategory::LengthOrPercentage = category(second) {
                    Position::new(Some(first), Some(second), None, None)
                } else {
                    Position::new(Some(first), None, None, Some(second))
                }
            } else {
                if let PositionCategory::LengthOrPercentage = category(second) {
                    Position::new(None, Some(second), Some(first), None)
                } else {
                    Position::new(None, None, Some(first), Some(second))
                }
            }
        }
    }
}

impl Keyword {
    pub fn to_length_or_percentage(self) -> LengthOrPercentage {
        match self {
            Keyword::Center => LengthOrPercentage::Percentage(Percentage(0.5)),
            Keyword::Left | Keyword::Top => LengthOrPercentage::Percentage(Percentage(0.0)),
            Keyword::Right | Keyword::Bottom => LengthOrPercentage::Percentage(Percentage(1.0)),
        }
    }
}

impl ToCss for Keyword {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
        match *self {
            Keyword::Center => try!(dest.write_str("center")),
            Keyword::Left => try!(dest.write_str("left")),
            Keyword::Right => try!(dest.write_str("right")),
            Keyword::Top => try!(dest.write_str("top")),
            Keyword::Bottom => try!(dest.write_str("bottom")),
        }
        Ok(())
    }
}

// Collapse `Position` into a few categories to simplify the above `match` expression.
enum PositionCategory {
    HorizontalKeyword,
    VerticalKeyword,
    OtherKeyword,
    LengthOrPercentage,
}

fn category(p: PositionComponent) -> PositionCategory {
    if let PositionComponent::Keyword(keyword) = p {
        match keyword {
            Keyword::Left |
            Keyword::Right =>
                PositionCategory::HorizontalKeyword,
            Keyword::Top |
            Keyword::Bottom =>
                PositionCategory::VerticalKeyword,
            Keyword::Center =>
                PositionCategory::OtherKeyword,
        }
    } else {
        PositionCategory::LengthOrPercentage
    }
}

impl ToComputedValue for Position {
    type ComputedValue = computed_position::Position;

    #[inline]
    fn to_computed_value(&self, context: &Context) -> computed_position::Position {
        let horiz_keyword = self.horiz_keyword.unwrap_or(Keyword::Left);
        let vert_keyword = self.vert_keyword.unwrap_or(Keyword::Top);

        // Construct horizontal computed LengthOrPercentage
        let horizontal = match horiz_keyword {
            Keyword::Right => {
                if let Some(x) = self.horiz_position {
                    let (length, percentage) = match x {
                        LengthOrPercentage::Percentage(Percentage(y)) => (None, Some(1.0 - y)),
                        LengthOrPercentage::Length(y) => (Some(-y.to_computed_value(context)), Some(1.0)),
                        _ => (None, None),
                    };
                    ComputedLengthOrPercentage::Calc(CalcLengthOrPercentage {
                        length: length,
                        percentage: percentage
                    })
                } else {
                    ComputedLengthOrPercentage::Percentage(1.0)
                }
            },
            Keyword::Center => {
                horiz_keyword.to_length_or_percentage().to_computed_value(context)
            },
             _ => {
                let horiz = self.horiz_position.unwrap_or(LengthOrPercentage::Percentage(Percentage(0.0)));
                horiz.to_computed_value(context)
            },
        };

        // Construct vertical computed LengthOrPercentage
        let vertical = match vert_keyword {
            Keyword::Bottom => {
                if let Some(x) = self.vert_position {
                    let (length, percentage) = match x {
                        LengthOrPercentage::Percentage(Percentage(y)) => (None, Some(1.0 - y)),
                        LengthOrPercentage::Length(y) => (Some(-y.to_computed_value(context)), Some(1.0)),
                        _ => (None, None),
                    };
                    ComputedLengthOrPercentage::Calc(CalcLengthOrPercentage {
                        length: length,
                        percentage: percentage
                    })
                } else {
                    ComputedLengthOrPercentage::Percentage(1.0)
                }
            },
            Keyword::Center => {
                vert_keyword.to_length_or_percentage().to_computed_value(context)
            },
             _ => {
                let vert = self.vert_position.unwrap_or(LengthOrPercentage::Percentage(Percentage(0.0)));
                vert.to_computed_value(context)
            },
        };

        computed_position::Position {
            horizontal: horizontal,
            vertical: vertical,
        }
    }
}

impl HasViewportPercentage for PositionComponent {
    fn has_viewport_percentage(&self) -> bool {
        match *self {
            PositionComponent::Length(length) => length.has_viewport_percentage(),
            _ => false
        }
    }
}

impl PositionComponent {
    pub fn parse(input: &mut Parser) -> Result<PositionComponent, ()> {
        input.try(LengthOrPercentage::parse)
        .map(PositionComponent::Length)
        .or_else(|()| {
            match try!(input.next()) {
                Token::Ident(value) => {
                    match_ignore_ascii_case! { value,
                        "center" => Ok(PositionComponent::Keyword(Keyword::Center)),
                        "left" => Ok(PositionComponent::Keyword(Keyword::Left)),
                        "right" => Ok(PositionComponent::Keyword(Keyword::Right)),
                        "top" => Ok(PositionComponent::Keyword(Keyword::Top)),
                        "bottom" => Ok(PositionComponent::Keyword(Keyword::Bottom)),
                        _ => Err(())
                    }
                },
                _ => Err(())
            }
        })
    }
    #[inline]
    pub fn to_length_or_percentage(self) -> LengthOrPercentage {
        match self {
            PositionComponent::Length(value) => value,
            PositionComponent::Keyword(keyword) => keyword.to_length_or_percentage(),
        }
    }
}