Exemplo n.º 1
0
        protected static void LoadCssXml(CssTreeParser parser, string styleSheet, XmlDocument xml)
        {
            ParseCssRemovingErrors(parser, styleSheet);
            var r = parser.Root;

            xml.LoadXml("<ROOT/>");
            AddSubTree(xml.DocumentElement, r, parser);
            ElaborateMultiSelectorRules(xml);
            if (!OutputXml)
            {
                return;
            }
            VerboseMessage("Writing XML stylesheet");
            WriteCssXml(styleSheet, xml);
        }
Exemplo n.º 2
0
        protected static void ParseCssRemovingErrors(CssTreeParser parser, string styleSheet)
        {
            var       error    = true;
            var       tryCount = 0;
            const int tryLimit = 20;

            while (error && tryCount < tryLimit)
            {
                try
                {
                    parser.Parse(styleSheet);
                    if (parser.Errors.Count > 0)
                    {
                        throw new Antlr.Runtime.RecognitionException(string.Format("{0} errors in CSS", parser.Errors.Count));
                    }
                    error = false;
                }
                catch (Exception)
                {
                    var outFullPath = MakeOutFullPath(styleSheet, "Bak.css");
                    File.Copy(styleSheet, outFullPath, true);
                    RemoveError(parser.Errors, styleSheet, 0);
                    tryCount += 1;
                    try
                    {
                        parser.Parse(styleSheet);
                        if (parser.Errors.Count > 0)
                        {
                            throw new Antlr.Runtime.RecognitionException(string.Format("{0} errors in CSS", parser.Errors.Count));
                        }
                        error = false;
                    }
                    catch (Exception)
                    {
                        error = true;
                        File.Copy(outFullPath, styleSheet, true);
                        RemoveError(parser.Errors, styleSheet, -1);
                        tryCount += 1;
                    }
                    File.Delete(outFullPath);
                }
            }
            if (tryCount >= tryLimit)
            {
                throw new Antlr.Runtime.RecognitionException(string.Format("{0} errors in {1}", parser.Errors.Count, styleSheet));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Do a single test.
        /// </summary>
        /// <param name="testName">Test name is also the folder containing the test.</param>
        /// <param name="msg">Message to display if failure occurs.</param>
        protected int OneTest(string styleSheet)
        {
            if (FileData.Get(styleSheet).Trim() == "")  // Skip empty files
            {
                return(0);
            }

            var ctp = new CssTreeParser();

            ctp.Parse(styleSheet);

            if (ctp.Errors.Count != 0)
            {
                Debug.Print(string.Format("{0} fails with {1} errors", Path.GetFileName(styleSheet), ctp.Errors.Count));
                return(1);
            }
            return(0);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Do a single test.
        /// </summary>
        /// <param name="testName">Test name is also the folder containing the test.</param>
        /// <param name="msg">Message to display if failure occurs.</param>
        protected void OneTest(string testName, string msg)
        {
            // Create input file name for test
            var inpFileName = Common.PathCombine(_inpPath, testName + ".css");

            var ctp = new CssTreeParser();

            ctp.Parse(inpFileName);
            var strResult = ctp.StringTree();

            // Output result to disk
            var outFileName = Common.PathCombine(_outPath, testName + ".txt");
            var sw          = new StreamWriter(outFileName);

            sw.Write(strResult);
            sw.Close();
            var expFileName = Common.PathCombine(_expPath, testName + ".txt");

            TextFileAssert.AreEqual(expFileName, outFileName, msg);

            if (ctp.Errors.Count != 0)
            {
                var strError        = ctp.ErrorText();
                var outErrorName    = Common.PathCombine(_outPath, testName + "Err.txt");
                var swe             = new StreamWriter(outErrorName);
                var strGenericError = Regex.Replace(strError, @"[\\/a-zA-Z0-9\:]+src", "src");
                swe.Write(strGenericError.Replace(@"\", "/"));
                swe.Close();
                var expErrorName = Common.PathCombine(_expPath, testName + "Err.txt");
                var msgErr       = msg + " in Error text";
                TextFileAssert.AreEqual(expErrorName, outErrorName, msgErr);
            }
            else
            {
                Assert.AreEqual(File.Exists(testName + "Err.txt"), false, msg + " error not generated");
            }
        }
Exemplo n.º 5
0
        protected static void AddSubTree(XmlNode n, CommonTree t, CssTreeParser ctp)
        {
            var argState = 0;
            var pos      = 0;
            var term     = 0;

            foreach (CommonTree child in ctp.Children(t))
            {
                var name   = child.Text;
                var first  = name.ToCharArray()[0];
                var second = '\0';
                if (name.Length > 1)
                {
                    second = name.ToCharArray()[1];
                }
                if (first >= 'A' && first <= 'Z' && second >= 'A' && second <= 'Z')
                {
                    Debug.Assert(n.OwnerDocument != null, "OwnerDocument != null");
                    var node = n.OwnerDocument.CreateElement(name);
                    if (name == "RULE") // later postion equals greater precedence
                    {
                        _lastClass = _target = "";
                        _noData    = false;
                        _term      = 0;
                    }
                    else if (name == "PROPERTY" && term == 0) // more terms equals greater precedence
                    {
                        term = _term;
                        var termAttr = n.OwnerDocument.CreateAttribute("term");
                        termAttr.Value = term.ToString();
                        if (_target != null && _target.StartsWith("stxfin"))
                        {
                            termAttr.Value = "99";
                        }
                        Debug.Assert(n.Attributes != null, "Attributes != null");
                        n.Attributes.Append(termAttr);
                    }
                    else
                    {
                        _term += 1;
                    }
                    n.AppendChild(node);
                    AddSubTree(node, child, ctp);
                    if (name == "RULE")
                    {
                        if (_noData)
                        {
                            Debug.Assert(node.ParentNode != null, "ParentNode != null");
                            node.ParentNode.RemoveChild(node);
                            continue;
                        }
                        pos += 1;
                        Debug.Assert(n.OwnerDocument != null, "OwnerDocument != null");
                        var posAttr = n.OwnerDocument.CreateAttribute("pos");
                        posAttr.Value = pos.ToString();
                        node.Attributes.Append(posAttr);
                        if (_lastClass != "")
                        {
                            var lastClassAttr = n.OwnerDocument.CreateAttribute("lastClass");
                            lastClassAttr.Value = _lastClass;
                            node.Attributes.Append(lastClassAttr);
                        }
                        if (_target != "")
                        {
                            var targetAttr = n.OwnerDocument.CreateAttribute("target");
                            targetAttr.Value = _target;
                            node.Attributes.Append(targetAttr);
                        }
                    }
                }
                else
                {
                    Debug.Assert(n.OwnerDocument != null, "OwnerDocument != null");
                    var node = n.OwnerDocument.CreateElement(argState == 0? "name": (argState & 1) == 1? "value": "unit");
                    argState      += 1;
                    node.InnerText = name;
                    n.AppendChild(node);
                    if (n.Name == "CLASS")
                    {
                        if (UniqueClasses != null && !UniqueClasses.Contains(name))
                        {
                            _noData = true;
                        }
                        _target = name;
                        if (!NeedHigher.Contains(name))
                        {
                            _lastClass = name;
                        }
                        else
                        {
                            VerboseMessage("skipping: {0}", name);
                        }
                    }
                    if (n.Name == "TAG")
                    {
                        _target = name;
                    }
                    AddSubTree(node, child, ctp);
                }
            }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            // ReSharper disable AssignNullToNotNullAttribute
            XmlCss.Load(XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(
                                             "CssSimpler.XmlCss.xsl")));
            SimplifyXhtml.Load(XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(
                                                    "CssSimpler.XhtmlSimplify.xsl"), ReaderSettings), XsltSettings, new NullResolver());
            // ReSharper enable AssignNullToNotNullAttribute
            // see: http://stackoverflow.com/questions/491595/best-way-to-parse-command-line-arguments-in-c
            var p = new OptionSet
            {
                {
                    "x|xml", "produce XML output of CSS",
                    v => OutputXml = !OutputXml
                },
                {
                    "b|backup", "make a backup of the original CSS file",
                    v => _makeBackup = !_makeBackup
                },
                {
                    "v|verbose", "increase debug message verbosity",
                    v =>
                    {
                        if (v != null)
                        {
                            ++_verbosity;
                        }
                    }
                },
                {
                    "h|help", "show this message and exit",
                    v => _showHelp = !_showHelp
                },
                {
                    "f|flat", "flattens the hierarchy simplifies the css required for -secmrd",
                    v => _flatten = !_flatten
                },
                {
                    "s|structure", "Use header tags for structure (1-3)",
                    v => _headerStyles += 1
                },
                {
                    "e|embed", "embed styles in output",
                    v => _embedStyles = !_embedStyles
                },
                //{
                //    "c|combine", "combine main and reversal(s) in a single output",
                //    v => _combineMainRev = !_combineMainRev
                //},
                {
                    "m|meta", "include title and author meta data",
                    v => _incMeta = !_incMeta
                },
                {
                    "r|remove", "remove Xml header and DOCTYPE",
                    v => _noXmlHeader = !_noXmlHeader
                },
                {
                    "d|div", "replace span with div for display block",
                    v => _divBlocks = !_divBlocks
                },
                {
                    "p|prefix=", "prefix style names with value",
                    v => { _decorateStyles = v; }
                },
                {
                    "u|update", "report status",
                    v => ReportStatus = !ReportStatus
                },
            };

            List <string> extra;

            try
            {
                extra = p.Parse(args);
                if (extra.Count == 0)
                {
                    Console.WriteLine(@"Enter full file name to process");
                    extra.Add(Console.ReadLine());
                }
            }
            catch (OptionException e)
            {
                Console.Write(@"SimpleCss: ");
                Console.WriteLine(e.Message);
                Console.WriteLine(@"Try `CssSimple --help' for more information.");
                return;
            }
            if (_showHelp || extra.Count != 1)
            {
                ShowHelp(p);
                return;
            }
            var lc = new LoadClasses(extra[0]);

            EntryReportInit();
            var styleSheet = lc.StyleSheet;

            MakeBackupIfNecessary(styleSheet, extra[0]);
            DebugWriteClassNames(lc.UniqueClasses);
            VerboseMessage("Clean up Stylesheet: {0}", styleSheet);
            var parser = new CssTreeParser();
            var xml    = new XmlDocument();

            UniqueClasses = lc.UniqueClasses;
            if (!File.Exists(styleSheet))
            {
                var errName  = styleSheet;
                var proposed = extra[0].Replace(".xhtml", ".css");
                styleSheet = proposed;
                if (!File.Exists(proposed))
                {
                    proposed   = proposed.Replace("_", "");
                    styleSheet = proposed;
                    if (!File.Exists(proposed))
                    {
                        proposed = Path.Combine(Path.GetDirectoryName(proposed), "main.css");
                        if (!File.Exists(proposed))
                        {
                            throw new FileNotFoundException(errName);
                        }
                        File.Copy(proposed, styleSheet, true);
                    }
                }
            }
            LoadCssXml(parser, styleSheet, xml);
            var tmpXhtmlFullName = WriteSimpleXhtml(extra[0]);
            var tmp2Out          = Path.GetTempFileName();
            // ReSharper disable once UnusedVariable
            var inlineStyle = new MoveInlineStyles(tmpXhtmlFullName, tmp2Out, styleSheet);

            xml.RemoveAll();
            UniqueClasses = null;
            LoadCssXml(parser, styleSheet, xml);
            // ReSharper disable once UnusedVariable
            var ps = new ProcessPseudo(tmp2Out, extra[0], xml, NeedHigher);

            RemoveCssPseudo(styleSheet, xml);
            var tmp3Out = Path.GetTempFileName();

            if (_flatten)
            {
                var fs = new FlattenStyles(extra[0], tmp3Out, xml, NeedHigher, _noXmlHeader, _decorateStyles);
                fs.Structure = _headerStyles;
                fs.DivBlocks = _divBlocks;
                MetaData(fs);
                fs.Parse();
                File.Copy(tmp3Out, extra[0], true);
                if (OutputXml)
                {
                    SavedXmlCssFileName = FlatXmlName(styleSheet);
                }
                OutputFlattenedStylesheet(extra[0], styleSheet, fs);
            }
            try
            {
                File.Delete(tmpXhtmlFullName);
                File.Delete(tmp2Out);
                File.Delete(tmp3Out);
            }
            catch
            {
                // ignored
            }
        }