/* This Source Code Form is subject to the terms of the Mozilla Public *License,v.2.0.IfacopyoftheMPLwasnotdistributedwiththis
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Style sheets and their CSS rules.
mod appearance_base_rule; pubmod container_rule; mod counter_style_rule; mod document_rule; mod font_face_rule; pubmod font_feature_values_rule; pubmod font_palette_values_rule; pubmod import_rule; pubmod keyframes_rule; pubmod layer_rule; mod loader; mod margin_rule; mod media_rule; mod namespace_rule; mod nested_declarations_rule; pubmod origin; mod page_rule; pubmod position_try_rule; mod property_rule; mod rule_list; mod rule_parser; mod rules_iterator; pubmod scope_rule; mod starting_style_rule; mod style_rule; mod stylesheet; pubmod supports_rule; pubmod view_transition_rule;
usecrate::derives::*; #[cfg(feature = "gecko")] usecrate::gecko_bindings::sugar::refptr::RefCounted; #[cfg(feature = "gecko")] usecrate::gecko_bindings::{bindings, structs}; usecrate::parser::{NestingContext, ParserContext}; usecrate::properties::{parse_property_declaration_list, PropertyDeclarationBlock}; usecrate::shared_lock::{DeepCloneWithLock, Locked}; usecrate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use cssparser::{parse_one_rule, Parser, ParserInput}; #[cfg(feature = "gecko")] use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf}; use servo_arc::Arc; use std::borrow::Cow; use std::fmt::{self, Write}; #[cfg(feature = "gecko")] use std::mem::{self, ManuallyDrop}; use style_traits::{CssStringWriter, ParsingMode}; use to_shmem::{SharedMemoryBuilder, ToShmem};
/// The CORS mode used for a CSS load. #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, PartialEq, ToShmem)] pubenum CorsMode { /// No CORS mode, so cross-origin loads can be done.
None, /// Anonymous CORS request.
Anonymous,
}
/// Extra data that the backend may need to resolve url values. /// /// If the usize's lowest bit is 0, then this is a strong reference to a /// structs::URLExtraData object. /// /// Otherwise, shifting the usize's bits the right by one gives the /// UserAgentStyleSheetID value corresponding to the style sheet whose /// URLExtraData this is, which is stored in URLExtraData_sShared. We don't /// hold a strong reference to that object from here, but we rely on that /// array's objects being held alive until shutdown. /// /// We use this packed representation rather than an enum so that /// `from_ptr_ref` can work. #[cfg(feature = "gecko")] // Although deriving MallocSizeOf means it always returns 0, that is fine because UrlExtraData // objects are reference-counted. #[derive(MallocSizeOf, PartialEq)] #[repr(C)] pubstruct UrlExtraData(usize);
/// Extra data that the backend may need to resolve url values. #[cfg(feature = "servo")] #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq)] pubstruct UrlExtraData(#[ignore_malloc_size_of = "Arc"] pub Arc<::url::Url>);
#[cfg(feature = "servo")] impl UrlExtraData { /// True if this URL scheme is chrome. pubfn chrome_rules_enabled(&self) -> bool { self.0.scheme() == "chrome"
}
/// Get the interior Url as a string. pubfn as_str(&self) -> &str { self.0.as_str()
}
}
#[cfg(feature = "gecko")] impl Drop for UrlExtraData { fn drop(&mutself) { // No need to release when we have an index into URLExtraData_sShared. ifself.0 & 1 == 0 { unsafe { self.as_ref().release();
}
}
}
}
#[cfg(feature = "gecko")] impl ToShmem for UrlExtraData { fn to_shmem(&self, _builder: &mut SharedMemoryBuilder) -> to_shmem::Result<Self> { ifself.0 & 1 == 0 { let shared_extra_datas = unsafe {
std::ptr::addr_of!(structs::URLExtraData_sShared)
.as_ref()
.unwrap()
}; let self_ptr = self.as_ref() as *const _ as *mut _; let sheet_id = shared_extra_datas
.iter()
.position(|r| r.mRawPtr == self_ptr); let sheet_id = match sheet_id {
Some(id) => id,
None => { return Err(String::from( "ToShmem failed for UrlExtraData: expected sheet's URLExtraData to be in \
URLExtraData::sShared",
));
},
};
Ok(ManuallyDrop::new(UrlExtraData((sheet_id << 1) | 1)))
} else {
Ok(ManuallyDrop::new(UrlExtraData(self.0)))
}
}
}
#[cfg(feature = "gecko")] impl UrlExtraData { /// Create a new UrlExtraData wrapping a pointer to the specified Gecko /// URLExtraData object. pubfn new(ptr: *mut structs::URLExtraData) -> UrlExtraData { unsafe {
(*ptr).addref();
}
UrlExtraData(ptr as usize)
}
/// True if this URL scheme is chrome. #[inline] pubfn chrome_rules_enabled(&self) -> bool { self.as_ref().mChromeRulesEnabled
}
/// Create a reference to this `UrlExtraData` from a reference to pointer. /// /// The pointer must be valid and non null. /// /// This method doesn't touch refcount. #[inline] pubunsafefn from_ptr_ref(ptr: &*mut structs::URLExtraData) -> &n style='color:red'>Self {
mem::transmute(ptr)
}
/// Returns a pointer to the Gecko URLExtraData object. pubfn ptr(&self) -> *mut structs::URLExtraData { ifself.0 & 1 == 0 { self.0as *mut structs::URLExtraData
} else { unsafe { let sheet_id = self.0 >> 1;
structs::URLExtraData_sShared[sheet_id].mRawPtr
}
}
}
// XXX We probably need to figure out whether we should mark Eq here. // It is currently marked so because properties::UnparsedValue wants Eq. #[cfg(feature = "gecko")] impl Eq for UrlExtraData {}
/// Serialize a page or style rule, starting with the opening brace. /// /// https://drafts.csswg.org/cssom/#serialize-a-css-rule CSSStyleRule /// /// This is not properly specified for page-rules, but we will apply the /// same process. fn style_or_page_rule_to_css(
rules: Option<&Arc<Locked<CssRules>>>,
block: &Locked<PropertyDeclarationBlock>,
guard: &SharedRwLockReadGuard,
dest: &mut CssStringWriter,
) -> fmt::Result { // Write the opening brace. The caller needs to serialize up to this point.
dest.write_char('{')?;
// Step 2 let declaration_block = block.read_with(guard); let has_declarations = !declaration_block.declarations().is_empty();
// Step 3 iflet Some(ref rules) = rules { let rules = rules.read_with(guard); // Step 6 (here because it's more convenient) if !rules.is_empty() { if has_declarations {
dest.write_str("\n ")?;
declaration_block.to_css(dest)?;
} return rules.to_css_block_without_opening(guard, dest);
}
}
/// A CSS rule. /// /// TODO(emilio): Lots of spec links should be around. #[derive(Clone, Debug, ToShmem)] #[allow(missing_docs)] pubenum CssRule {
Style(Arc<Locked<StyleRule>>), // No Charset here, CSSCharsetRule has been removed from CSSOM // https://drafts.csswg.org/cssom/#changes-from-5-december-2013
Namespace(Arc<NamespaceRule>),
Import(Arc<Locked<ImportRule>>),
Media(Arc<MediaRule>),
CustomMedia(Arc<CustomMediaRule>),
Container(Arc<ContainerRule>),
FontFace(Arc<Locked<FontFaceRule>>),
FontFeatureValues(Arc<FontFeatureValuesRule>),
FontPaletteValues(Arc<FontPaletteValuesRule>),
CounterStyle(Arc<Locked<CounterStyleRule>>),
Keyframes(Arc<Locked<KeyframesRule>>),
Margin(Arc<MarginRule>),
Supports(Arc<SupportsRule>),
Page(Arc<Locked<PageRule>>),
Property(Arc<PropertyRule>),
Document(Arc<DocumentRule>),
LayerBlock(Arc<LayerBlockRule>),
LayerStatement(Arc<LayerStatementRule>),
Scope(Arc<ScopeRule>),
StartingStyle(Arc<StartingStyleRule>),
AppearanceBase(Arc<AppearanceBaseRule>),
PositionTry(Arc<Locked<PositionTryRule>>),
NestedDeclarations(Arc<Locked<NestedDeclarationsRule>>),
ViewTransition(Arc<ViewTransitionRule>),
}
impl CssRule { /// Measure heap usage. #[cfg(feature = "gecko")] fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { match *self { // Not all fields are currently fully measured. Extra measurement // may be added later.
CssRule::Namespace(_) => 0,
// We don't need to measure ImportRule::stylesheet because we measure // it on the C++ side in the child list of the ServoStyleSheet.
CssRule::Import(_) => 0,
// These aliases are required on Gecko side to avoid generating bindings for `Locked`. /// Alias for a locked style rule. pubtype LockedStyleRule = Locked<StyleRule>; /// Alias for a locked import rule. pubtype LockedImportRule = Locked<ImportRule>; /// Alias for a locked font-face rule. pubtype LockedFontFaceRule = Locked<FontFaceRule>; /// Alias for a locked counter-style rule. pubtype LockedCounterStyleRule = Locked<CounterStyleRule>; /// Alias for a locked keyframes rule. pubtype LockedKeyframesRule = Locked<KeyframesRule>; /// Alias for a locked page rule. pubtype LockedPageRule = Locked<PageRule>; /// Alias for a locked position-try rule. pubtype LockedPositionTryRule = Locked<PositionTryRule>; /// Alias for a locked nested declarations rule. pubtype LockedNestedDeclarationsRule = Locked<NestedDeclarationsRule>;
let state = if !insert_rule_context.containing_rule_types.is_empty() {
State::Body
} elseif insert_rule_context.index == 0 {
State::Start
} else { let index = insert_rule_context.index;
insert_rule_context.max_rule_state_at_index(index - 1)
};
let error = parser.dom_error.take().unwrap_or(RulesMutateError::Syntax); // If new rule is a syntax error, and nested is set, perform the following substeps: if matches!(error, RulesMutateError::Syntax) && parser.can_parse_declarations() { let declarations = parse_property_declaration_list(&parser.context, &mut input, &[]); if !declarations.is_empty() { return Ok(CssRule::NestedDeclarations(Arc::new(
parser.shared_lock.wrap(NestedDeclarationsRule {
block: Arc::new(parser.shared_lock.wrap(declarations)),
source_location: input.current_source_location(),
}),
)));
}
}
Err(error)
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.