private IEnumerable <ParseItem> GetItems(string file, CssParser parser, string searchValue) { StyleSheet ss = parser.Parse(File.ReadAllText(file), true); var visitorClass = new CssItemCollector <ClassSelector>(true); ss.Accept(visitorClass); var classes = from c in visitorClass.Items where c.Text.Contains(searchValue) select c; var visitorIDs = new CssItemCollector <IdSelector>(true); ss.Accept(visitorIDs); var ids = from c in visitorIDs.Items where c.Text.Contains(searchValue) select c; List <ParseItem> list = new List <ParseItem>(); list.AddRange(classes); list.AddRange(ids); return(list); }
public IEnumerable <ICssCompletionListEntry> GetListEntries(CssCompletionContext context) { if (!IsFontFamilyContext(context)) { yield break; } StyleSheet stylesheet = context.ContextItem.StyleSheet; var visitorRules = new CssItemCollector <FontFaceDirective>(); stylesheet.Accept(visitorRules); foreach (FontFaceDirective item in visitorRules.Items) { var visitorDec = new CssItemCollector <Declaration>(); item.Block.Accept(visitorDec); Declaration family = visitorDec.Items.FirstOrDefault(i => i.PropertyName.Text == "font-family"); if (family != null) { string value = string.Join(string.Empty, family.Values.Select(v => v.Text)); yield return(new FontFamilyCompletionListEntry(value.Trim('\'', '"'))); } } yield return(new FontFamilyCompletionListEntry("Pick from file...")); }
protected static IList <T> FindCssItems <T>(StyleSheet stylesheet) where T : ParseItem { var visitor = new CssItemCollector <T>(true); stylesheet.Accept(visitor); return(visitor.Items); }
private static void ParseDocument() { string fileName = GetSolutionFilePath(); if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName)) { CssParser parser = new CssParser(); StyleSheet stylesheet = parser.Parse(File.ReadAllText(fileName), false); if (stylesheet.IsValid) { var visitor = new CssItemCollector <AtDirective>(); stylesheet.Accept(visitor); AtDirective at = visitor.Items.SingleOrDefault(a => a.Keyword.Text == _rootDirective); if (at != null) { var visitorPalette = new CssItemCollector <AtDirective>(true); at.Accept(visitorPalette); _directives = visitorPalette.Items.Where(a => a.Keyword.Text != at.Keyword.Text).ToList(); } } InitializeWatcher(fileName); } else { _hasFile = false; } }
public IEnumerable <ICssCompletionListEntry> GetListEntries(CssCompletionContext context) { HashSet <ICssCompletionListEntry> entries = new HashSet <ICssCompletionListEntry>(); Declaration dec = context.ContextItem.FindType <Declaration>(); if (dec == null || dec.PropertyName == null || (!dec.PropertyName.Text.EndsWith("animation-name", StringComparison.OrdinalIgnoreCase) && dec.PropertyName.Text != "animation")) { return(entries); } StyleSheet stylesheet = context.ContextItem.StyleSheet; var visitor = new CssItemCollector <KeyFramesDirective>(); stylesheet.Accept(visitor); foreach (KeyFramesDirective keyframes in visitor.Items) { if (!entries.Any(e => e.DisplayText.Equals(keyframes.Name.Text, StringComparison.OrdinalIgnoreCase))) { entries.Add(new CompletionListEntry(keyframes.Name.Text)); } } return(entries); }
CheckQuestionReferences(StyleSheet styleSheet, QuestionForm questionForm) { var checker = new QLSReferenceChecker(); questionForm.Accept(checker); styleSheet.Accept(checker); return(checker._messages.ToTuple()); }
public void TreeVisitor_VisitTest1() { string text = Helpers.LoadFileAsString(@"Files\090\91.css"); CssParser p = new CssParser(); StyleSheet s = p.Parse(text, true); SimpleTreeVisitor simpleVisitor = new SimpleTreeVisitor(); s.Accept(simpleVisitor); Assert.AreEqual(12913, simpleVisitor.CountCalls); }
public IEnumerable <ICssCompletionListEntry> GetListEntries(CssCompletionContext context) { StyleSheet stylesheet = context.ContextItem.StyleSheet; var visitorRules = new CssItemCollector <IdSelector>(); stylesheet.Accept(visitorRules); foreach (string item in visitorRules.Items.Where(s => s != context.ContextItem).Select(s => s.Text).Distinct()) { yield return(new CompletionListEntry(item)); } }
private void InitializeCache(StyleSheet stylesheet) { _cache.Clear(); var visitor = new CssItemCollector<Declaration>(true); stylesheet.Accept(visitor); foreach (Declaration dec in visitor.Items.Where(d => d.PropertyName != null)) { if (dec.PropertyName.Text == "display" && dec.Values.Any(v => v.Text == "inline")) _cache.Add(dec); } }
private void InitializeCache(StyleSheet stylesheet) { _cache.Clear(); var visitor = new CssItemCollector <Declaration>(true); stylesheet.Accept(visitor); foreach (Declaration dec in visitor.Items.Where(d => d.PropertyName != null)) { if (dec.PropertyName.Text == "display" && dec.Values.Any(v => v.Text == "inline")) { _cache.Add(dec); } } }
public IEnumerable <ICssCompletionListEntry> GetListEntries(CssCompletionContext context) { Declaration dec = context.ContextItem.FindType <Declaration>(); if (dec == null || dec.PropertyName == null || (!dec.PropertyName.Text.EndsWith("animation-name", StringComparison.OrdinalIgnoreCase) && dec.PropertyName.Text != "animation")) { yield break; } StyleSheet stylesheet = context.ContextItem.StyleSheet; var visitor = new CssItemCollector <KeyFramesDirective>(); stylesheet.Accept(visitor); foreach (string name in visitor.Items.Select(d => d.Name.Text).Distinct(StringComparer.OrdinalIgnoreCase)) { yield return(new CompletionListEntry(name)); } }
public IEnumerable <ICssCompletionListEntry> GetListEntries(CssCompletionContext context) { HashSet <string> classNames = new HashSet <string>(); HashSet <ICssCompletionListEntry> entries = new HashSet <ICssCompletionListEntry>(); StyleSheet stylesheet = context.ContextItem.StyleSheet; var visitorRules = new CssItemCollector <ClassSelector>(); stylesheet.Accept(visitorRules); foreach (ClassSelector item in visitorRules.Items) { if (item != context.ContextItem && !classNames.Contains(item.Text)) { classNames.Add(item.Text); entries.Add(new CompletionListEntry(item.Text)); } } return(entries); }
private string PreprocessorSorting(StyleSheet stylesheet) { StringBuilder sb = new StringBuilder(stylesheet.Text); var visitor = new CssItemCollector <CssRuleBlock>(true); stylesheet.Accept(visitor); foreach (var rule in visitor.Items.Where(r => r.IsValid).Reverse()) { if (rule.Children.Count < 2) { continue; } int start = rule.OpenCurlyBrace.AfterEnd; int length = rule.Length - 1; length = AdjustLength(rule, start, length); if (length < 1) { continue; } string text = GetNormalizedText(rule, start, length); string[] declarations = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); //.Where(t => !string.IsNullOrWhiteSpace(t)).ToArray(); var sorted = SortDeclarations2(declarations); sb.Remove(start, length - 1); sb.Insert(start, string.Join("", sorted)); } return(sb.ToString()); }
public string SortStyleSheet(string css) { ICssParser parser = new CssParser(); StyleSheet stylesheet = parser.Parse(css.Trim(), true); CssFormatter formatter = new CssFormatter(); formatter.Options.RemoveLastSemicolon = false; StringBuilder sb = new StringBuilder(stylesheet.Text); var visitor = new CssItemCollector <RuleBlock>(true); stylesheet.Accept(visitor); foreach (RuleBlock rule in visitor.Items.Where(r => r.IsValid).Reverse()) { if (rule.Declarations.Count <= 1) { continue; } int start = rule.OpenCurlyBrace.AfterEnd; int length = rule.Length - 2; string text = formatter.Format(rule.Text).Trim().Trim('}', '{'); string[] declarations = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var sorted = SortDeclarations(declarations); sb.Remove(start, length); sb.Insert(start, string.Join("", sorted)); } return(sb.ToString()); }
public void TreeVisitor_VisitTest2() { string text = @" <!-- @charset 'utf-8'; @foo { } @font-face { foo: bar } @namespace foo bar; @import url('foo'); @page { @margin { } } @media not screen { .foo { } } @keyframes foo { from { } } .foo[foo] { } --> "; CssParser p = new CssParser(); StyleSheet s = p.Parse(text, true); SimpleTreeVisitor simpleVisitor = new SimpleTreeVisitor(); s.Accept(simpleVisitor); Assert.AreEqual(102, simpleVisitor.CountCalls); }
private string FindRuleSetInFile(IEnumerable <string> extensions, string id, out RuleSet rule) { string root = ProjectHelpers.GetProjectFolder(peekableItem._textbuffer.GetFileName()); string result = null; bool isLow = false, isMedium = false; rule = null; foreach (string ext in extensions) { ICssParser parser = CssParserLocator.FindComponent(ProjectHelpers.GetContentType(ext.Trim('.'))).CreateParser(); foreach (string file in Directory.EnumerateFiles(root, "*" + ext, SearchOption.AllDirectories)) { if (file.EndsWith(".min" + ext, StringComparison.OrdinalIgnoreCase) || file.Contains("node_modules") || file.Contains("bower_components") || file.Contains("\\obj\\Release") || file.Contains("\\obj\\Debug\\") || file.Contains("\\obj\\publish\\")) { continue; } string text = File.ReadAllText(file); int index = text.IndexOf("#" + id, StringComparison.Ordinal); if (index == -1) { continue; } StyleSheet css = parser.Parse(text, true); var visitor = new CssItemCollector <IdSelector>(false); css.Accept(visitor); IEnumerable <IdSelector> selectors = visitor.Items.Where(c => c.HashName.Text == "#" + id); IdSelector high = selectors.FirstOrDefault(c => c.FindType <AtDirective>() == null && (c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ",")); if (high != null) { rule = high.FindType <RuleSet>(); return(file); } IdSelector medium = selectors.FirstOrDefault(c => c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ","); if (medium != null && !isMedium) { rule = medium.FindType <RuleSet>(); result = file; isMedium = true; continue; } IdSelector low = selectors.FirstOrDefault(); if (low != null && !isMedium && !isLow) { rule = low.FindType <RuleSet>(); result = file; isLow = true; continue; } } } return(result); }
public void ParseFile(string name) { StreamReader streamReader = null; StreamWriter streamWriter = null; string file = name + ".tree"; try { string text = Helpers.LoadFileAsString(name); ITextProvider textProvider = new StringTextProvider(text); CssParser parser = new CssParser(); #if TEST_MEM_USAGE long startMem = GC.GetTotalMemory(true); long totalTokenizeMS = 0; long totalParseMS = 0; StyleSheet[] styleSheets = new StyleSheet[32]; for (int i = 0; i < styleSheets.Length; i++) { styleSheets[i] = parser.Parse(textProvider, insertComments: true); totalTokenizeMS += parser.LastTokenizeMilliseconds; totalParseMS += parser.LastParseMilliseconds; } StyleSheet styleSheet = styleSheets[0]; long items = 0; styleSheet.Accept(new CssTreeVisitor((ParseItem) => { items++; return(VisitItemResult.Continue); })); long endMem = GC.GetTotalMemory(true); long totalMem = endMem - startMem; long avgMem = totalMem / styleSheets.Length; totalTokenizeMS /= styleSheets.Length; totalParseMS /= styleSheets.Length; _totalMemParseFile += avgMem; _totalCharsParseFile += text.Length; _totalItemsParseFile += items; _totalTokenizeMS += totalTokenizeMS; _totalParseMS += totalParseMS; System.Diagnostics.Debug.WriteLine("CSS parse file: {0}", file); System.Diagnostics.Debug.WriteLine("----------------------------------------------------------------------"); System.Diagnostics.Debug.WriteLine(" Mem usage: {0} bytes for {1} chars ({2} bytes per char)", avgMem, text.Length, avgMem / text.Length); System.Diagnostics.Debug.WriteLine(" Mem usage: {0} bytes for {1} items ({2} bytes per item)", avgMem, items, avgMem / items); System.Diagnostics.Debug.WriteLine(" Perf: Tokenize:{0}ms, Parse:{1}ms, Total:{2}ms", totalTokenizeMS, totalParseMS, totalTokenizeMS + totalParseMS); System.Diagnostics.Debug.WriteLine( " Running mem usage average: {0} bytes per char. {1} bytes per item.", _totalMemParseFile / _totalCharsParseFile, _totalMemParseFile / _totalItemsParseFile); #else StyleSheet styleSheet = parser.Parse(text, insertComments: true); #endif DebugWriter debugWriter = new DebugWriter(); string actual = debugWriter.Serialize(textProvider, styleSheet); if (s_regenerateBaselineFiles) { if (File.Exists(file)) { File.SetAttributes(file, FileAttributes.Normal); } streamWriter = new StreamWriter(file); streamWriter.Write(actual); streamWriter.Close(); streamWriter = null; } else { streamReader = new StreamReader(file); string expected = streamReader.ReadToEnd(); streamReader.Close(); streamReader = null; // trim whitescpase in the end to avoid false positives b/c file // has extra line break or whitespace at the end. expected = expected.TrimEnd(new char[] { ' ', '\r', '\n', '\t' }); actual = actual.TrimEnd(new char[] { ' ', '\r', '\n', '\t' }); Assert.AreEqual(expected, actual); } } catch (Exception exception) { Assert.Fail(string.Format("Test {0} has thrown an exception: {1}", name.Substring(name.LastIndexOf('\\') + 1), exception.Message)); } finally { if (streamReader != null) { streamReader.Close(); } if (streamWriter != null) { streamWriter.Close(); } } }
private string PreprocessorSorting(StyleSheet stylesheet) { StringBuilder sb = new StringBuilder(stylesheet.Text); var visitor = new CssItemCollector<CssRuleBlock>(true); stylesheet.Accept(visitor); foreach (var rule in visitor.Items.Where(r => r.IsValid).Reverse()) { if (rule.Children.Count < 2) continue; int start = rule.OpenCurlyBrace.AfterEnd; int length = rule.Length - 1; length = AdjustLength(rule, start, length); if (length < 1) continue; string text = GetNormalizedText(rule, start, length); string[] declarations = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); //.Where(t => !string.IsNullOrWhiteSpace(t)).ToArray(); var sorted = SortDeclarations2(declarations); sb.Remove(start, length - 1); sb.Insert(start, string.Join("", sorted)); } return sb.ToString(); }
public Control Render() { _styleSheet.Accept(this); _controlContainer.Size = new Size(1000, 1000); return(_controlContainer); }