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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
|
/* 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 https://mozilla.org/MPL/2.0/. */
//! Specified types for CSS values related to borders.
use crate::parser::{Parse, ParserContext};
use crate::values::computed::border::BorderSideWidth as ComputedBorderSideWidth;
use crate::values::computed::{Context, ToComputedValue};
use crate::values::generics::border::{
GenericBorderCornerRadius, GenericBorderImageSideWidth, GenericBorderImageSlice,
GenericBorderRadius, GenericBorderSpacing,
};
use crate::values::generics::rect::Rect;
use crate::values::generics::size::Size2D;
use crate::values::specified::length::{Length, NonNegativeLength, NonNegativeLengthPercentage};
use crate::values::specified::Color;
use crate::values::specified::{AllowQuirks, NonNegativeNumber, NonNegativeNumberOrPercentage};
use crate::Zero;
use app_units::Au;
use cssparser::Parser;
use std::fmt::{self, Write};
use style_traits::{values::SequenceWriter, CssWriter, ParseError, ToCss};
/// A specified value for a single side of a `border-style` property.
///
/// The order here corresponds to the integer values from the border conflict
/// resolution rules in CSS 2.1 ยง 17.6.2.1. Higher values override lower values.
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(
Clone,
Copy,
Debug,
Eq,
FromPrimitive,
MallocSizeOf,
Ord,
Parse,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
ToTyped,
)]
#[repr(u8)]
pub enum BorderStyle {
Hidden,
None,
Inset,
Groove,
Outset,
Ridge,
Dotted,
Dashed,
Solid,
Double,
}
impl BorderStyle {
/// Whether this border style is either none or hidden.
#[inline]
pub fn none_or_hidden(&self) -> bool {
matches!(*self, BorderStyle::None | BorderStyle::Hidden)
}
}
/// A specified value for the `border-image-width` property.
pub type BorderImageWidth = Rect<BorderImageSideWidth>;
/// A specified value for a single side of a `border-image-width` property.
pub type BorderImageSideWidth =
GenericBorderImageSideWidth<NonNegativeLengthPercentage, NonNegativeNumber>;
/// A specified value for the `border-image-slice` property.
pub type BorderImageSlice = GenericBorderImageSlice<NonNegativeNumberOrPercentage>;
/// A specified value for the `border-radius` property.
pub type BorderRadius = GenericBorderRadius<NonNegativeLengthPercentage>;
/// A specified value for the `border-*-radius` longhand properties.
pub type BorderCornerRadius = GenericBorderCornerRadius<NonNegativeLengthPercentage>;
/// A specified value for the `border-spacing` longhand properties.
pub type BorderSpacing = GenericBorderSpacing<NonNegativeLength>;
impl BorderImageSlice {
/// Returns the `100%` value.
#[inline]
pub fn hundred_percent() -> Self {
GenericBorderImageSlice {
offsets: Rect::all(NonNegativeNumberOrPercentage::hundred_percent()),
fill: false,
}
}
}
/// https://drafts.csswg.org/css-backgrounds-3/#typedef-line-width
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped)]
pub enum LineWidth {
/// `thin`
Thin,
/// `medium`
Medium,
/// `thick`
Thick,
/// `<length>`
Length(NonNegativeLength),
}
impl LineWidth {
/// Returns the `0px` value.
#[inline]
pub fn zero() -> Self {
Self::Length(NonNegativeLength::zero())
}
fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
if let Ok(length) =
input.try_parse(|i| NonNegativeLength::parse_quirky(context, i, allow_quirks))
{
return Ok(Self::Length(length));
}
Ok(try_match_ident_ignore_ascii_case! { input,
"thin" => Self::Thin,
"medium" => Self::Medium,
"thick" => Self::Thick,
})
}
}
impl Parse for LineWidth {
fn parse<'i>(
context: &ParserContext,
input: &mut Parser<'i, '_>,
) -> Result<Self, ParseError<'i>> {
Self::parse_quirky(context, input, AllowQuirks::No)
}
}
impl ToComputedValue for LineWidth {
type ComputedValue = Au;
#[inline]
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self {
// https://drafts.csswg.org/css-backgrounds-3/#line-width
Self::Thin => Au::from_px(1),
Self::Medium => Au::from_px(3),
Self::Thick => Au::from_px(5),
Self::Length(ref length) => Au::from_f32_px(length.to_computed_value(context).px()),
}
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Self::Length(NonNegativeLength::from_px(computed.to_f32_px()))
}
}
/// A specified value for a single side of the `border-width` property. The difference between this
/// and LineWidth is whether we snap to device pixels or not.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped)]
pub struct BorderSideWidth(LineWidth);
impl BorderSideWidth {
/// Returns the `medium` value.
pub fn medium() -> Self {
Self(LineWidth::Medium)
}
/// Returns a bare px value from the argument.
pub fn from_px(px: f32) -> Self {
Self(LineWidth::Length(Length::from_px(px).into()))
}
/// Parses, with quirks.
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
Ok(Self(LineWidth::parse_quirky(context, input, allow_quirks)?))
}
}
impl Parse for BorderSideWidth {
fn parse<'i>(
context: &ParserContext,
input: &mut Parser<'i, '_>,
) -> Result<Self, ParseError<'i>> {
Self::parse_quirky(context, input, AllowQuirks::No)
}
}
// https://drafts.csswg.org/css-values-4/#snap-a-length-as-a-border-width
fn snap_as_border_width(len: Au, context: &Context) -> Au {
debug_assert!(len >= Au(0));
// Round `width` down to the nearest device pixel, but any non-zero value that would round
// down to zero is clamped to 1 device pixel.
if len == Au(0) {
return len;
}
let au_per_dev_px = context.device().app_units_per_device_pixel();
std::cmp::max(Au(au_per_dev_px), Au(len.0 / au_per_dev_px * au_per_dev_px))
}
impl ToComputedValue for BorderSideWidth {
type ComputedValue = ComputedBorderSideWidth;
#[inline]
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
ComputedBorderSideWidth(snap_as_border_width(
self.0.to_computed_value(context),
context,
))
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Self(LineWidth::from_computed_value(&computed.0))
}
}
/// A specified value for outline-offset.
#[derive(
Clone, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToCss, ToShmem, ToTyped,
)]
#[typed_value(derive_fields)]
pub struct BorderSideOffset(Length);
impl ToComputedValue for BorderSideOffset {
type ComputedValue = Au;
#[inline]
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
let offset = Au::from_f32_px(self.0.to_computed_value(context).px());
let should_snap = match static_prefs::pref!("layout.css.outline-offset.snapping") {
1 => true,
2 => context.device().chrome_rules_enabled_for_document(),
_ => false,
};
if !should_snap {
return offset;
}
if offset < Au(0) {
-snap_as_border_width(-offset, context)
} else {
snap_as_border_width(offset, context)
}
}
#[inline]
fn from_computed_value(computed: &Au) -> Self {
Self(Length::from_px(computed.to_f32_px()))
}
}
impl BorderImageSideWidth {
/// Returns `1`.
#[inline]
pub fn one() -> Self {
GenericBorderImageSideWidth::Number(NonNegativeNumber::new(1.))
}
}
impl Parse for BorderImageSlice {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let mut fill = input.try_parse(|i| i.expect_ident_matching("fill")).is_ok();
let offsets = Rect::parse_with(context, input, NonNegativeNumberOrPercentage::parse)?;
if !fill {
fill = input.try_parse(|i| i.expect_ident_matching("fill")).is_ok();
}
Ok(GenericBorderImageSlice { offsets, fill })
}
}
impl Parse for BorderRadius {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let widths = Rect::parse_with(context, input, NonNegativeLengthPercentage::parse)?;
let heights = if input.try_parse(|i| i.expect_delim('/')).is_ok() {
Rect::parse_with(context, input, NonNegativeLengthPercentage::parse)?
} else {
widths.clone()
};
Ok(GenericBorderRadius {
top_left: BorderCornerRadius::new(widths.0, heights.0),
top_right: BorderCornerRadius::new(widths.1, heights.1),
bottom_right: BorderCornerRadius::new(widths.2, heights.2),
bottom_left: BorderCornerRadius::new(widths.3, heights.3),
})
}
}
impl Parse for BorderCornerRadius {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Size2D::parse_with(context, input, NonNegativeLengthPercentage::parse)
.map(GenericBorderCornerRadius)
}
}
impl Parse for BorderSpacing {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Size2D::parse_with(context, input, |context, input| {
NonNegativeLength::parse_quirky(context, input, AllowQuirks::Yes)
})
.map(GenericBorderSpacing)
}
}
/// A single border-image-repeat keyword.
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(u8)]
pub enum BorderImageRepeatKeyword {
Stretch,
Repeat,
Round,
Space,
}
/// The specified value for the `border-image-repeat` property.
///
/// https://drafts.csswg.org/css-backgrounds/#the-border-image-repeat
#[derive(
Clone,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToResolvedValue,
ToShmem,
ToTyped,
)]
#[repr(C)]
pub struct BorderImageRepeat(pub BorderImageRepeatKeyword, pub BorderImageRepeatKeyword);
impl ToCss for BorderImageRepeat {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.0.to_css(dest)?;
if self.0 != self.1 {
dest.write_char(' ')?;
self.1.to_css(dest)?;
}
Ok(())
}
}
impl BorderImageRepeat {
/// Returns the `stretch` value.
#[inline]
pub fn stretch() -> Self {
BorderImageRepeat(
BorderImageRepeatKeyword::Stretch,
BorderImageRepeatKeyword::Stretch,
)
}
}
impl Parse for BorderImageRepeat {
fn parse<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let horizontal = BorderImageRepeatKeyword::parse(input)?;
let vertical = input.try_parse(BorderImageRepeatKeyword::parse).ok();
Ok(BorderImageRepeat(
horizontal,
vertical.unwrap_or(horizontal),
))
}
}
/// Serializes a border shorthand value composed of width/style/color.
pub fn serialize_directional_border<W>(
dest: &mut CssWriter<W>,
width: &BorderSideWidth,
style: &BorderStyle,
color: &Color,
) -> fmt::Result
where
W: Write,
{
let has_style = *style != BorderStyle::None;
let has_color = *color != Color::CurrentColor;
let has_width = *width != BorderSideWidth::medium();
if !has_style && !has_color && !has_width {
return width.to_css(dest);
}
let mut writer = SequenceWriter::new(dest, " ");
if has_width {
writer.item(width)?;
}
if has_style {
writer.item(style)?;
}
if has_color {
writer.item(color)?;
}
Ok(())
}
|