示例#1
0
        public void Import(UnityStyleSheet asset, string contents)
        {
            ParserStyleSheet styleSheet = m_Parser.Parse(contents);

            if (styleSheet.Errors.Count > 0)
            {
                foreach (StylesheetParseError error in styleSheet.Errors)
                {
                    m_Errors.AddSyntaxError(error.ToString());
                }
            }
            else
            {
                try
                {
                    VisitSheet(styleSheet);
                }
                catch (Exception exc)
                {
                    Debug.LogException(exc);
                    m_Errors.AddInternalError(exc.StackTrace);
                }
            }

            if (!m_Errors.hasErrors)
            {
                m_Builder.BuildTo(asset);
                OnImportSuccess(asset);
            }
            else
            {
                OnImportError(m_Errors);
            }
        }
        void VisitSheet(ParserStyleSheet styleSheet)
        {
            foreach (ParserStyleRule rule in styleSheet.StyleRules)
            {
                m_Builder.BeginRule(rule.Line);

                m_CurrentLine = rule.Line;

                // Note: we must rely on recursion to correctly handle parser types here
                VisitBaseSelector(rule.Selector);

                foreach (Property property in rule.Declarations)
                {
                    m_CurrentLine = property.Line;

                    ValidateProperty(property);

                    m_Builder.BeginProperty(property.Name, property.Line);

                    // Note: we must rely on recursion to correctly handle parser types here
                    VisitValue(property.Term);

                    m_Builder.EndProperty();
                }

                m_Builder.EndRule();
            }
        }
示例#3
0
        public bool Import(UnityStyleSheet asset, string contents)
        {
            ParserStyleSheet styleSheet = m_Parser.Parse(contents);

            if (styleSheet.Errors.Count > 0)
            {
                foreach (StylesheetParseError error in styleSheet.Errors)
                {
                    m_Errors.AddSyntaxError(error.ToString());
                }
            }
            else
            {
                try
                {
                    VisitSheet(styleSheet);
                }
                catch (Exception exc)
                {
                    m_Errors.AddInternalError(exc.Message);
                }
            }

            if (!m_Errors.hasErrors)
            {
                m_Builder.BuildTo(asset);
            }

            return(!m_Errors.hasErrors);
        }
        public void TestBadCss()
        {
            StylesheetParser ExCssParser = new StylesheetParser();

            foreach (string Filename in CssBadDocs.Keys)
            {
                string     CssData       = CssBadDocs[Filename];
                Stylesheet CssStylesheet = ExCssParser.Parse(CssData);
                Assert.IsNotNull(CssStylesheet, string.Format("FAIL: {0}", Filename));
            }
        }
        public void Import(UnityStyleSheet asset, string contents)
        {
            ParserStyleSheet styleSheet = m_Parser.Parse(contents);

            ImportParserStyleSheet(asset, styleSheet);

            var h = new Hash128();

            byte[] b = Encoding.UTF8.GetBytes(contents);
            if (b.Length > 0)
            {
                HashUtilities.ComputeHash128(b, ref h);
            }
            asset.contentHash = h.GetHashCode();
        }
        protected void ImportParserStyleSheet(UnityStyleSheet asset, ParserStyleSheet styleSheet)
        {
            m_Errors.assetPath = assetPath;

            if (styleSheet.Errors.Count > 0)
            {
                foreach (StylesheetParseError error in styleSheet.Errors)
                {
                    m_Errors.AddSyntaxError(error.ToString());
                }
            }
            else
            {
                try
                {
                    VisitSheet(styleSheet);
                }
                catch (Exception exc)
                {
                    Debug.LogException(exc);
                    m_Errors.AddInternalError(exc.StackTrace);
                }
            }

            bool success = !m_Errors.hasErrors;

            if (success)
            {
                m_Builder.BuildTo(asset);
                OnImportSuccess(asset);
            }

            if (!success || m_Errors.hasWarning)
            {
                OnImportError(m_Errors);
            }
        }
        protected void ImportParserStyleSheet(UnityStyleSheet asset, ParserStyleSheet styleSheet)
        {
            m_Errors.assetPath = assetPath;

            if (styleSheet.Errors.Count > 0)
            {
                foreach (StylesheetParseError error in styleSheet.Errors)
                {
                    m_Errors.AddSyntaxError(error.ToString());
                }
            }
            else
            {
                try
                {
                    VisitSheet(styleSheet);
                }
                catch (Exception exc)
                {
                    Debug.LogException(exc);
                    m_Errors.AddInternalError(exc.StackTrace);
                }
            }

            bool success = !m_Errors.hasErrors;

            if (success)
            {
                m_Builder.BuildTo(asset);

                if (!s_StyleSheetsWithCircularImportDependencies.Contains(assetPath))
                {
                    var importDirectivesCount = styleSheet.ImportDirectives.Count;
                    asset.imports = new UnityStyleSheet.ImportStruct[importDirectivesCount];
                    for (int i = 0; i < importDirectivesCount; ++i)
                    {
                        var importedPath = styleSheet.ImportDirectives[i].Href;

                        string projectRelativePath, errorMessage;

                        URIValidationResult importResult = URIHelpers.ValidAssetURL(assetPath, importedPath, out errorMessage, out projectRelativePath);

                        UnityStyleSheet importedStyleSheet = null;
                        if (importResult != URIValidationResult.OK)
                        {
                            m_Errors.AddSemanticError(ConvertErrorCode(importResult), errorMessage);
                        }
                        else
                        {
                            importedStyleSheet = DeclareDependencyAndLoad(projectRelativePath) as UnityStyleSheet;
                            m_Context.DependsOnImportedAsset(projectRelativePath);
                        }

                        asset.imports[i] = new UnityStyleSheet.ImportStruct
                        {
                            styleSheet   = importedStyleSheet,
                            mediaQueries = styleSheet.ImportDirectives[i].Media.ToArray()
                        };
                    }

                    if (importDirectivesCount > 0)
                    {
                        asset.FlattenImportedStyleSheetsRecursive();
                    }
                }
                else
                {
                    asset.imports = new UnityStyleSheet.ImportStruct[0];
                    var errorMsg = $"The {assetPath} contains circular @import dependencies. All @import directives will be ignored for this StyleSheet.";
                    Debug.LogError(errorMsg);
                    m_Errors.AddInternalError(errorMsg);
                }

                OnImportSuccess(asset);
            }

            if (!success || m_Errors.hasWarning)
            {
                OnImportError(m_Errors);
            }
        }
        public void Import(UnityStyleSheet asset, string contents)
        {
            ParserStyleSheet styleSheet = m_Parser.Parse(contents);

            ImportParserStyleSheet(asset, styleSheet);
        }
        /** -------------------------------------------------------------------- **/

        private async Task _ProcessCssPage()
        {
            MacroscopeHttpTwoClient         Client   = this.DocCollection.GetJobMaster().GetHttpClient();
            MacroscopeHttpTwoClientResponse Response = null;
            string ResponseErrorCondition            = null;

            DebugMsg(string.Format("ProcessCssPage: {0}", ""));

            try
            {
                Response = await Client.Get(
                    this.GetUri(),
                    this.ConfigureCssPageRequestHeadersCallback,
                    this.PostProcessRequestHttpHeadersCallback
                    );
            }
            catch (MacroscopeDocumentException ex)
            {
                this.DebugMsg(string.Format("_ProcessCssPage :: MacroscopeDocumentException: {0}", ex.Message));
                ResponseErrorCondition = ex.Message;
                this.SetStatusCode(HttpStatusCode.BadRequest);
                this.AddRemark("_ProcessCssPage", ex.Message);
            }
            catch (Exception ex)
            {
                this.DebugMsg(string.Format("_ProcessCssPage :: Exception: {0}", ex.Message));
                ResponseErrorCondition = ex.Message;
                this.SetStatusCode(HttpStatusCode.BadRequest);
                this.AddRemark("_ProcessCssPage", ex.Message);
            }

            if (Response != null)
            {
                string RawData = "";

                this.ProcessResponseHttpHeaders(Response: Response);

                /** Get Response Body ---------------------------------------------- **/

                try
                {
                    DebugMsg(string.Format("MIME TYPE: {0}", this.MimeType));

                    RawData = Response.GetContentAsString();

                    this.SetContentLength(Length: RawData.Length); // May need to find bytes length

                    this.SetWasDownloaded(true);
                }
                catch (Exception ex)
                {
                    DebugMsg(string.Format("Exception: {0}", ex.Message));
                    this.SetStatusCode(HttpStatusCode.Ambiguous);
                    this.SetContentLength(Length: 0);
                }

                if (!string.IsNullOrEmpty(RawData))
                {
                    try
                    {
                        StylesheetParser CssParser     = new StylesheetParser();
                        Stylesheet       CssStylesheet = CssParser.Parse(RawData);
                        this.ProcessCssOutlinks(CssStylesheet: CssStylesheet);
                    }
                    catch (Exception ex)
                    {
                        this.DebugMsg(string.Format("ProcessHtmlAttributeCssLinks: {0}", ex.Message));
                        this.AddRemark("ProcessHtmlAttributeCssLinks", ex.Message);
                    }
                }
                else
                {
                    DebugMsg(string.Format("ProcessCssPage: ERROR: {0}", this.GetUrl()));
                }

                /** Custom Filters ------------------------------------------------- **/

                if (!string.IsNullOrEmpty(RawData))
                {
                    if (
                        MacroscopePreferencesManager.GetCustomFiltersEnable() &&
                        MacroscopePreferencesManager.GetCustomFiltersApplyToCss())
                    {
                        MacroscopeCustomFilters CustomFilter = this.DocCollection.GetJobMaster().GetCustomFilter();

                        if ((CustomFilter != null) && (CustomFilter.IsEnabled()))
                        {
                            this.ProcessGenericCustomFiltered(
                                CustomFilter: CustomFilter,
                                GenericText: RawData
                                );
                        }
                    }
                }

                /** Data Extractors ------------------------------------------------ **/

                if (!string.IsNullOrEmpty(RawData))
                {
                    if (
                        MacroscopePreferencesManager.GetDataExtractorsEnable() &&
                        MacroscopePreferencesManager.GetDataExtractorsApplyToCss())
                    {
                        this.ProcessGenericDataExtractors(GenericText: RawData);
                    }
                }

                /** Title ---------------------------------------------------------- **/

                {
                    MatchCollection reMatches     = Regex.Matches(this.DocUrl, "/([^/]+)$");
                    string          DocumentTitle = null;
                    foreach (Match match in reMatches)
                    {
                        if (match.Groups[1].Value.Length > 0)
                        {
                            DocumentTitle = match.Groups[1].Value.ToString();
                            break;
                        }
                    }
                    if (DocumentTitle != null)
                    {
                        this.SetTitle(DocumentTitle, MacroscopeConstants.TextProcessingMode.NO_PROCESSING);
                        DebugMsg(string.Format("TITLE: {0}", this.GetTitle()));
                    }
                    else
                    {
                        DebugMsg(string.Format("TITLE: {0}", "MISSING"));
                    }
                }
            }

            if (ResponseErrorCondition != null)
            {
                this.ProcessErrorCondition(ResponseErrorCondition);
            }
        }
        /**************************************************************************/

        private void ProcessCssOutlinks(Stylesheet CssStylesheet)
        {
            if (this.GetIsExternal())
            {
                return;
            }

            foreach (var CssRule in CssStylesheet.StyleRules)
            {
                int iRule = CssStylesheet.StyleRules.IndexOf(CssRule);

                foreach (Property pProp in CssStylesheet.StyleRules[iRule].Declarations.Properties)
                {
                    string BackgroundImageUrl;
                    string LinkUrlAbs;

                    switch (pProp.Name.ToLower())
                    {
                    case "background-image":

                        if (pProp.Term != null)
                        {
                            BackgroundImageUrl = pProp.Term.ToString();
                            LinkUrlAbs         = this.ProcessCssBackImageUrl(BackgroundImageUrl);

                            DebugMsg(string.Format("ProcessCssHyperlinksOut: (background-image): {0}", BackgroundImageUrl));
                            DebugMsg(string.Format("ProcessCssHyperlinksOut: (background-image): {0}", LinkUrlAbs));

                            if (LinkUrlAbs != null)
                            {
                                MacroscopeHyperlinkOut HyperlinkOut = null;
                                MacroscopeLink         Outlink      = null;

                                HyperlinkOut = this.HyperlinksOut.Add(
                                    LinkType: MacroscopeConstants.HyperlinkType.CSS,
                                    UrlTarget: LinkUrlAbs
                                    );

                                Outlink = this.AddDocumentOutlink(
                                    AbsoluteUrl: LinkUrlAbs,
                                    LinkType: MacroscopeConstants.InOutLinkType.IMAGE,
                                    Follow: true
                                    );

                                if (Outlink != null)
                                {
                                    Outlink.SetRawTargetUrl(BackgroundImageUrl);
                                }
                            }
                        }

                        break;

                    case "background":

                        if (pProp.Term != null)
                        {
                            BackgroundImageUrl = pProp.Term.ToString();
                            LinkUrlAbs         = this.ProcessCssBackImageUrl(BackgroundImageUrl);

                            DebugMsg(string.Format("ProcessCssHyperlinksOut: (background): {0}", BackgroundImageUrl));
                            DebugMsg(string.Format("ProcessCssHyperlinksOut: (background): {0}", LinkUrlAbs));

                            if (LinkUrlAbs != null)
                            {
                                MacroscopeHyperlinkOut HyperlinkOut = null;
                                MacroscopeLink         Outlink      = null;

                                HyperlinkOut = this.HyperlinksOut.Add(
                                    LinkType: MacroscopeConstants.HyperlinkType.CSS,
                                    UrlTarget: LinkUrlAbs
                                    );

                                Outlink = this.AddDocumentOutlink(
                                    AbsoluteUrl: LinkUrlAbs,
                                    LinkType: MacroscopeConstants.InOutLinkType.IMAGE,
                                    Follow: true
                                    );

                                if (Outlink != null)
                                {
                                    Outlink.SetRawTargetUrl(BackgroundImageUrl);
                                }
                            }
                        }

                        break;

                    default:
                        break;
                    }
                }
            }
        }
        protected void ImportParserStyleSheet(UnityStyleSheet asset, ParserStyleSheet styleSheet)
        {
            m_Errors.assetPath = assetPath;

            if (styleSheet.Errors.Count > 0)
            {
                foreach (StylesheetParseError error in styleSheet.Errors)
                {
                    m_Errors.AddSyntaxError(string.Format(glossary.ussParsingError, error.Message), error.Line);
                }
            }
            else
            {
                try
                {
                    VisitSheet(styleSheet);
                }
                catch (System.Exception exc)
                {
                    m_Errors.AddInternalError(string.Format(glossary.internalErrorWithStackTrace, exc.Message, exc.StackTrace), m_CurrentLine);
                }
            }

            bool hasErrors = m_Errors.hasErrors;

            if (!hasErrors)
            {
                m_Builder.BuildTo(asset);

                if (!s_StyleSheetsWithCircularImportDependencies.Contains(assetPath))
                {
                    var importDirectivesCount = styleSheet.ImportDirectives.Count;
                    asset.imports = new UnityStyleSheet.ImportStruct[importDirectivesCount];
                    for (int i = 0; i < importDirectivesCount; ++i)
                    {
                        var importedPath = styleSheet.ImportDirectives[i].Href;

                        var response            = URIHelpers.ValidateAssetURL(assetPath, importedPath);
                        var importResult        = response.result;
                        var errorToken          = response.errorToken;
                        var projectRelativePath = response.resolvedProjectRelativePath;

                        if (response.hasWarningMessage)
                        {
                            m_Errors.AddValidationWarning(response.warningMessage, m_CurrentLine);
                        }

                        UnityStyleSheet importedStyleSheet = null;
                        if (importResult != URIValidationResult.OK)
                        {
                            var(code, message) = ConvertErrorCode(importResult);
                            m_Errors.AddSemanticWarning(code, string.Format(message, errorToken), m_CurrentLine);
                        }
                        else
                        {
                            importedStyleSheet = response.resolvedQueryAsset as UnityStyleSheet;
                            if (importedStyleSheet)
                            {
                                m_Context.DependsOnSourceAsset(projectRelativePath);
                            }
                            else
                            {
                                importedStyleSheet = DeclareDependencyAndLoad(projectRelativePath) as UnityStyleSheet;
                            }

                            if (!response.isLibraryAsset)
                            {
                                m_Context.DependsOnImportedAsset(projectRelativePath);
                            }
                        }

                        asset.imports[i] = new UnityStyleSheet.ImportStruct
                        {
                            styleSheet   = importedStyleSheet,
                            mediaQueries = styleSheet.ImportDirectives[i].Media.ToArray()
                        };
                    }

                    if (importDirectivesCount > 0)
                    {
                        asset.FlattenImportedStyleSheetsRecursive();
                    }
                }
                else
                {
                    asset.imports = new UnityStyleSheet.ImportStruct[0];
                    m_Errors.AddValidationWarning(glossary.circularImport, -1);
                }

                OnImportSuccess(asset);
            }

            bool hasWarnings = m_Errors.hasWarning;

            asset.importedWithErrors   = hasErrors;
            asset.importedWithWarnings = hasWarnings;

            if (hasErrors || hasWarnings)
            {
                OnImportError(m_Errors);
            }
        }
示例#12
0
        /**************************************************************************/

        private void ProcessCssPage()
        {
            HttpWebRequest  req = null;
            HttpWebResponse res = null;
            string          ResponseErrorCondition = null;
            Boolean         IsAuthenticating       = false;

            DebugMsg(string.Format("ProcessCssPage: {0}", ""));

            try
            {
                req           = WebRequest.CreateHttp(this.DocUrl);
                req.Method    = "GET";
                req.Timeout   = this.Timeout;
                req.KeepAlive = false;
                req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                this.PrepareRequestHttpHeaders(req: req);

                IsAuthenticating = this.AuthenticateRequest(req);

                MacroscopePreferencesManager.EnableHttpProxy(req);

                res = ( HttpWebResponse )req.GetResponse();
            }
            catch (UriFormatException ex)
            {
                DebugMsg(string.Format("ProcessCssPage :: UriFormatException: {0}", ex.Message));
                ResponseErrorCondition = ex.Message;
            }
            catch (TimeoutException ex)
            {
                DebugMsg(string.Format("ProcessCssPage :: TimeoutException: {0}", ex.Message));
                ResponseErrorCondition = ex.Message;
            }
            catch (WebException ex)
            {
                DebugMsg(string.Format("ProcessCssPage :: WebException: {0}", ex.Message));
                DebugMsg(string.Format("ProcessCssPage :: WebException: {0}", ex.Status));
                DebugMsg(string.Format("ProcessCssPage :: WebException: {0}", ( int )ex.Status));

                ResponseErrorCondition = ex.Status.ToString();
            }

            if (res != null)
            {
                string RawData = "";

                this.ProcessResponseHttpHeaders(req, res);

                if (IsAuthenticating)
                {
                    this.VerifyOrPurgeCredential();
                }

                // Get Response Body
                try
                {
                    DebugMsg(string.Format("MIME TYPE: {0}", this.MimeType));

                    Stream       ResponseStream = res.GetResponseStream();
                    StreamReader ResponseStreamReader;

                    if (this.GetCharacterEncoding() != null)
                    {
                        ResponseStreamReader = new StreamReader(ResponseStream, this.GetCharacterEncoding());
                    }
                    else
                    {
                        ResponseStreamReader = new StreamReader(ResponseStream);
                    }

                    RawData = ResponseStreamReader.ReadToEnd();

                    this.ContentLength = RawData.Length; // May need to find bytes length

                    this.SetWasDownloaded(true);
                }
                catch (WebException ex)
                {
                    DebugMsg(string.Format("WebException: {0}", ex.Message));

                    if (ex.Response != null)
                    {
                        this.SetStatusCode((( HttpWebResponse )ex.Response).StatusCode);
                    }
                    else
                    {
                        this.SetStatusCode(( HttpStatusCode )ex.Status);
                    }

                    RawData            = "";
                    this.ContentLength = 0;
                }
                catch (Exception ex)
                {
                    DebugMsg(string.Format("Exception: {0}", ex.Message));
                    this.SetStatusCode(HttpStatusCode.BadRequest);
                    this.ContentLength = 0;
                }

                if (!string.IsNullOrEmpty(RawData))
                {
                    ExCSS.Parser     ExCssParser     = new ExCSS.Parser();
                    ExCSS.StyleSheet ExCssStylesheet = ExCssParser.Parse(RawData);

                    this.ProcessCssOutlinks(ExCssStylesheet);
                }
                else
                {
                    DebugMsg(string.Format("ProcessCssPage: ERROR: {0}", this.GetUrl()));
                }

                /** Custom Filters ------------------------------------------------- **/

                if (!string.IsNullOrEmpty(RawData))
                {
                    if (
                        MacroscopePreferencesManager.GetCustomFiltersEnable() &&
                        MacroscopePreferencesManager.GetCustomFiltersApplyToCss())
                    {
                        MacroscopeCustomFilters CustomFilter = this.DocCollection.GetJobMaster().GetCustomFilter();

                        if ((CustomFilter != null) && (CustomFilter.IsEnabled()))
                        {
                            this.ProcessGenericCustomFiltered(
                                CustomFilter: CustomFilter,
                                GenericText: RawData
                                );
                        }
                    }
                }

                /** Data Extractors ------------------------------------------------ **/

                if (!string.IsNullOrEmpty(RawData))
                {
                    if (
                        MacroscopePreferencesManager.GetDataExtractorsEnable() &&
                        MacroscopePreferencesManager.GetDataExtractorsApplyToCss())
                    {
                        this.ProcessGenericDataExtractors(GenericText: RawData);
                    }
                }

                /** Title ---------------------------------------------------------- **/

                {
                    MatchCollection reMatches     = Regex.Matches(this.DocUrl, "/([^/]+)$");
                    string          DocumentTitle = null;
                    foreach (Match match in reMatches)
                    {
                        if (match.Groups[1].Value.Length > 0)
                        {
                            DocumentTitle = match.Groups[1].Value.ToString();
                            break;
                        }
                    }
                    if (DocumentTitle != null)
                    {
                        this.SetTitle(DocumentTitle, MacroscopeConstants.TextProcessingMode.NO_PROCESSING);
                        DebugMsg(string.Format("TITLE: {0}", this.GetTitle()));
                    }
                    else
                    {
                        DebugMsg(string.Format("TITLE: {0}", "MISSING"));
                    }
                }

                res.Close();

                res.Dispose();
            }

            if (ResponseErrorCondition != null)
            {
                this.ProcessErrorCondition(ResponseErrorCondition);
            }
        }