public void LoadFromStream(Stream stream) { var parser = new StylesheetParser (); parser.Parse(stream); Stylesheet = parser.Stylesheet; }
public void LoadFromString(string content) { var parser = new StylesheetParser(); parser.Parse (content); Stylesheet = parser.Stylesheet; }
public static void Css() { var parser = new StylesheetParser(); var stylesheet = parser.Parse(".someClass{color: red; background-image: url('/images/logo.png')"); //var noo = stylesheet.RuleSets.First().Selectors.First().SimpleSelectors.First(). //var imageUrl = stylesheet.RuleSets // .SelectMany(r => r.Declarations).First(). // .SelectMany(d => d.Expression.Terms).First(t => t.Type == TermType.Url); // Finds the '/images/logo.png' image }
private static void AddExCssStyle(this IXLWorksheet worksheet, int rowId, int colId, HtmlNode cell) { var css = cell.GetAttributeValue("style", ""); var parser = new StylesheetParser(); var stylesheet = parser.Parse(css); SimpleSelector color = stylesheet.RuleSets.SelectMany(x => x.Selectors) .SelectMany(x => x.SimpleSelectors) .FirstOrDefault(x => x.ElementName == "color"); string thing = (color == null) ? "" : color.Child.Pseudo; worksheet.Cell(rowId, colId).Style.Font.FontColor = XLColor.FromName(thing); }
public static IDictionary<string, BaseStyle> ParceCss(string content) { var parser = new StylesheetParser(); var styles = parser.Parse(content); var rules = styles.RuleSets.ToArray(); var result = rules.ToDictionary( rule => rule.Selectors.First().SimpleSelectors.First().Class, rule => new StyleFactory(rule.Declarations).Style); return result; }
private async Task ProcessCss(IDotvvmRequestContext context) { Modified = false; var getCodeTasks = resources.Select(t => GetCode(t, context)).ToArray(); Task.WaitAll(getCodeTasks); var strings = getCodeTasks.Select(t => t.Result).ToArray(); var code = string.Join(string.Empty, strings); if (string.IsNullOrWhiteSpace(code)) { ampCustomCode = string.Empty; ampKeyFramesCode = string.Empty; return; } CheckStyleCodeForPrematureEnding(code); var parser = new ExCSS.StylesheetParser(true, true, true, true, true); var stylesheet = await parser.ParseAsync(code); var styleRules = new StringBuilder(); var keyframeRules = new StringBuilder(); ampValidator.CheckStylesheet(stylesheet); foreach (var styleRule in stylesheet.Children) { if (configuration.StyleRemoveForbiddenImportant) { foreach (var property in GetAllProperties(styleRule)) { property.IsImportant = false; } } if (styleRule is IKeyframeRule keyframe) { keyframeRules.Append(keyframe.ToCss()); } else { styleRules.Append(styleRule.ToCss()); } } ampCustomCode = MinifiCss(styleRules.ToString()); ampKeyFramesCode = MinifiCss(keyframeRules.ToString()); }
public static Rule CreateRule(this StylesheetParser parser, RuleType type) { switch (type) { case RuleType.Charset: return(new CharsetRule(parser)); case RuleType.Document: return(new DocumentRule(parser)); case RuleType.FontFace: return(new FontFaceRule(parser)); case RuleType.Import: return(new ImportRule(parser)); case RuleType.Keyframe: return(new KeyframeRule(parser)); case RuleType.Keyframes: return(new KeyframesRule(parser)); case RuleType.Media: return(new MediaRule(parser)); case RuleType.Namespace: return(new NamespaceRule(parser)); case RuleType.Page: return(new PageRule(parser)); case RuleType.Style: return(new StyleRule(parser)); case RuleType.Supports: return(new SupportsRule(parser)); case RuleType.Viewport: return(new ViewportRule(parser)); case RuleType.Unknown: case RuleType.RegionStyle: case RuleType.FontFeatureValues: case RuleType.CounterStyle: default: return(null); } }
public static void ConvertRelativeUrlsToAbsolute(CombinatorResource resource, Uri baseUrl) { if (String.IsNullOrEmpty(resource.Content)) return; var stylesheet = new StylesheetParser().Parse(resource.Content); // Modifying relative urls (because when saved, local urls were converted to unified relative ones) to point to the original domain ProcessUrls( resource, stylesheet, (ruleSet, urlTerm) => { if (Uri.IsWellFormedUriString(urlTerm.Value, UriKind.Absolute)) return; urlTerm.Value = new Uri(baseUrl, urlTerm.Value).ToProtocolRelative(); }); }
public void ProcessResource(CombinatorResource resource, StringBuilder combinedContent, ICombinatorSettings settings) { if (resource.IsCdnResource && !settings.CombineCDNResources) { resource.IsOriginal = true; return; } var absoluteUrlString = resource.AbsoluteUrl.ToString(); _resourceFileService.LoadResourceContent(resource); _eventHandler.OnContentLoaded(resource); if (String.IsNullOrEmpty(resource.Content)) return; if (resource.Type == ResourceType.Style) { var stylesheet = new StylesheetParser().Parse(resource.Content); AdjustRelativePaths(resource, stylesheet); if (settings.EmbedCssImages && (settings.EmbedCssImagesStylesheetExcludeFilter == null || !settings.EmbedCssImagesStylesheetExcludeFilter.IsMatch(absoluteUrlString))) { EmbedImages(resource, stylesheet, settings.EmbeddedImagesMaxSizeKB); } resource.Content = stylesheet.ToString(); } if (settings.MinifyResources && (settings.MinificationExcludeFilter == null || !settings.MinificationExcludeFilter.IsMatch(absoluteUrlString))) { MinifyResourceContent(resource); if (String.IsNullOrEmpty(resource.Content)) return; } _eventHandler.OnContentProcessed(resource); combinedContent.Append(resource.Content); }
/// <summary> Gets the CSS classes. </summary> /// <returns> The CSS classes. </returns> public static StyleSheet GetStyleSheet() { string pdfStyleSheet = OutputSettings.Instance.StyleSheet; if (string.IsNullOrWhiteSpace(pdfStyleSheet)) { return null; } StylesheetParser ssp = new StylesheetParser(); string css = File.ReadAllText(HttpContext.Current.Server.MapPath(pdfStyleSheet)); Stylesheet stylesheet = ssp.Parse(css); StyleSheet styles = new StyleSheet(); foreach (RuleSet ruleSet in stylesheet.RuleSets) { Dictionary<string, string> attributes = ruleSet.Declarations.ToDictionary( declaration => declaration.Name, declaration => declaration.Expression.ToString()); foreach (Selector selector in ruleSet.Selectors) { if (selector.ToString().StartsWith(".", StringComparison.OrdinalIgnoreCase)) { styles.LoadStyle(selector.ToString(), attributes); } else { styles.LoadTagStyle(selector.ToString(), attributes); } } } return styles; }
public IEnumerable <ElementStyle> ParseStyles(string css) { var parser = new ExCSS.StylesheetParser(); var stylesheet = parser.Parse(css); foreach (var child in stylesheet.Children) { if (child is Rule rule) { if (rule.Type == RuleType.Style) { var style = new ElementStyle(); foreach (var ruleChild in rule.Children) { if (ruleChild is ISelector selector) { style.Keys.Add(selector.Text); } else if (ruleChild is StyleDeclaration declaration) { foreach (var prop in declaration.Children) { if (prop is Property property) { style.Properties.Add(property); } } } } yield return(style); } } } }
static void Main(string[] args) { restore(); Environment.Exit(0); List <FileInformation> AllCssFiles = getFileList(); backup(AllCssFiles); Console.WriteLine("目前一共" + AllCssFiles.Count.ToString() + "个主题样式!"); foreach (FileInformation item in AllCssFiles) { Console.WriteLine("正在处理:" + item.FullName); ExCSS.Stylesheet css = new ExCSS.StylesheetParser().Parse(item.Content); StyleRule stagestyle = css.Children.Single(x => ((StyleRule)x).SelectorText == "stage") as StyleRule; if (stagestyle != null) { string aa = stagestyle.Style.FontFamily; string pp = stagestyle.Style.FontSize; stagestyle.Style.SetPropertyValue("font-family", "Microsoft YaHei"); stagestyle.Style.SetPropertyValue("font-size", "12pt"); try { using (TextWriter writer = File.CreateText(item.FullName)) { writer.Write(css.ToCss()); } } catch (System.Exception e) { if (e is System.UnauthorizedAccessException) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("修改:" + item.FullName + " 时,执行权限不够,请提权后重试!"); System.Environment.Exit(0); } } } } }
internal DeclarationRule(RuleType type, string name, StylesheetParser parser) : base(type, parser) { _name = name; }
internal SupportsRule(StylesheetParser parser) : base(RuleType.Supports, parser) { }
public StylesheetComposer(Lexer lexer, StylesheetParser parser) { _lexer = lexer; _parser = parser; _nodes = new Stack <StylesheetNode>(); }
internal DocumentRule(StylesheetParser parser) : base(RuleType.Document, parser) { }
internal MediaRule(StylesheetParser parser) : base(RuleType.Media, parser) { AppendChild(new MediaList(parser)); }
internal KeyframeRule(StylesheetParser parser) : base(RuleType.Keyframe, parser) { AppendChild(new StyleDeclaration(this)); }
public void ReplaceCssImagesWithSprite(CombinatorResource resource) { Func<RuleSet, Term, bool> noSprite = (ruleSet, url) => { if (url.Value.Contains("no-sprite") || ruleSet.Selectors.Any(selector => selector.SimpleSelectors.Any(simpleSelector => simpleSelector.Class == "no-sprite"))) return true; // Images with a background position are not suitable for sprite generation if they aren't top-left if (ruleSet.Declarations.Any(declaration => declaration.Name == "background-position" && (declaration.Expression.Terms.Count() != 2 || !declaration.Expression.Terms.Any(term => term.Value == "top") || !declaration.Expression.Terms.Any(term => term.Value == "left")))) return true; // Images with a background size are not suitable for sprite generation if (ruleSet.Declarations.Any(declaration => declaration.Name == "background-size")) return true; // Images with a background repeat are not suitable for sprite generation if (ruleSet.Declarations.Any(declaration => declaration.Name == "background-repeat" && (declaration.Expression.Terms.Count() != 1 || declaration.Expression.Terms.First().Value != "no-repeat"))) return true; var backgroundTerms = ruleSet.Declarations .Where(declaration => declaration.Name == "background") .SelectMany(declaration => declaration.Expression.Terms); // Sized backgrounds are not suitable either // LineHeightTerm is filled with a value when if in the shorthand background declaration there's the background size specified, e.g.: // background: url(url-to-img) 300px 400px / 500px 600px no-repeat; // Now there will be a term for 400px, having LineHeightTerm specified for 500px. if (backgroundTerms.Any(term => term.LineHeightTerm != null)) return true; var backgroundTermValues = backgroundTerms.Select(term => term.Value); // Positioned backgrounds are not suitable either, except top-left ones if (backgroundTerms .Any(term => term.Value == "center" || term.Value == "top" || term.Value == "right" || term.Value == "bottom" || term.Unit != null) && !(backgroundTermValues.Contains("top") && backgroundTermValues.Contains("left"))) return true; if (backgroundTermValues.Any(value => value == "repeat-x" || value == "repeat-y" || value == "repeat")) return true; return false; }; var images = new Dictionary<string, CssImage>(); var stylesheet = new StylesheetParser().Parse(resource.Content); ProcessImageUrls( resource, stylesheet, (ruleSet, urlTerm) => { var url = urlTerm.Value; if (noSprite(ruleSet, urlTerm)) return; var imageContent = _resourceFileService.GetImageContent(InlineUriFactory(resource, url), 5000); if (imageContent != null) { images[url] = new CssImage { Content = imageContent }; } }); if (images.Count == 0) return; _cacheFileService.WriteSpriteStream( resource.Content.GetHashCode() + ".jpg", (stream, publicUrl) => { using (var sprite = new Sprite(images.Values.Select(image => image.Content))) { var imageEnumerator = images.Values.GetEnumerator(); foreach (var backgroundImage in sprite.Generate(stream, ImageFormat.Jpeg)) { imageEnumerator.MoveNext(); imageEnumerator.Current.BackgroundImage = backgroundImage; imageEnumerator.Current.BackgroundImage.Url = InlineUriFactory(resource, publicUrl); } } }); ProcessImageUrls( resource, stylesheet, (ruleSet, urlTerm) => { var url = urlTerm.Value; if (images.ContainsKey(url)) { var backgroundImage = images[url].BackgroundImage; var imageDeclaration = new Declaration { Name = "background-image", Expression = new Expression { Terms = new List<Term> { new Term { Type = TermType.Url, Value = backgroundImage.Url.ToProtocolRelative() } } } }; ruleSet.Declarations.Add(imageDeclaration); var bgPosition = backgroundImage.Position; var positionDeclaration = new Declaration { Name = "background-position", Expression = new Expression { Terms = new List<Term> { new Term { Type = TermType.Number, Value = bgPosition.X.ToString(), Unit = Unit.Px }, new Term { Type = TermType.Number, Value = bgPosition.Y.ToString(), Unit = Unit.Px } } } }; ruleSet.Declarations.Add(positionDeclaration); } }); resource.Content = stylesheet.ToString(); }
internal ImportRule(StylesheetParser parser) : base(RuleType.Import, parser) { AppendChild(new MediaList(parser)); }
internal PageRule(StylesheetParser parser) : base(RuleType.Page, parser) { AppendChild(SimpleSelector.All); AppendChild(new StyleDeclaration(this)); }
public UnknownRule(string name, StylesheetParser parser) : base(RuleType.Unknown, parser) { Name = name; }
internal CharsetRule(StylesheetParser parser) : base(RuleType.Charset, parser) { }
internal Stylesheet(StylesheetParser parser) { _parser = parser; Rules = new RuleList(this); }
internal MediaList(StylesheetParser parser) { _parser = parser; }
internal NamespaceRule(StylesheetParser parser) : base(RuleType.Namespace, parser) { }
internal KeyframesRule(StylesheetParser parser) : base(RuleType.Keyframes, parser) { Rules = new RuleList(this); }