示例#1
0
		public void ResolveNamespace(XElement elem, XamlContext ctx) {
			if (Namespace != null)
				return;

			// Since XmlnsProperty records are inside the element,
			// the namespace is resolved after processing the element body.

			string xmlNs = null;
			if (elem.Annotation<XmlnsScope>() != null)
				xmlNs = elem.Annotation<XmlnsScope>().LookupXmlns(Assembly, TypeNamespace);
			if (xmlNs == null)
				xmlNs = ctx.XmlNs.LookupXmlns(Assembly, TypeNamespace);

			if (xmlNs == null) {
				var nsSeg = TypeNamespace.Split('.');
				var nsName = nsSeg[nsSeg.Length - 1].ToLowerInvariant();
				var prefix = nsName;
				int count = 0;
				while (elem.GetNamespaceOfPrefix(prefix) != null) {
					count++;
					prefix = nsName + count;
				}

				xmlNs = string.Format("clr-namespace:{0};assembly={1}", TypeNamespace, Assembly);
				elem.Add(new XAttribute(XNamespace.Xmlns + XmlConvert.EncodeLocalName(prefix),
					ctx.GetXmlNamespace(xmlNs)));
			}
			Namespace = xmlNs;
		}
 public static ASupportElement GetInstance(XElement definition)
 {
     Type eType = ElementType (definition);
     if (eType != null) {
         if (definition.Annotation (eType) != null)
             return definition.Annotation (eType) as ASupportElement;
         else {
             var instance = Activator.CreateInstance (eType, new object[] { definition });
             definition.AddAnnotation (instance);
             return instance as ASupportElement;
         }
     } else
         return null;
 }
示例#3
0
		void RewriteClass(XamlContext ctx, XElement elem) {
			var type = elem.Annotation<XamlType>();
			if (type == null || type.ResolvedType == null)
				return;

			var typeDef = type.ResolvedType.ResolveTypeDef();
			var comparer = new AssemblyNameComparer(AssemblyNameComparerFlags.All);
			if (typeDef == null || !comparer.Equals(typeDef.DefinitionAssembly, ctx.Module.Assembly))
				return;

			var newType = typeDef.BaseType;
			var xamlType = new XamlType(newType.DefinitionAssembly, newType.ReflectionNamespace, newType.Name);
			xamlType.ResolveNamespace(elem, ctx);

			elem.Name = xamlType.ToXName(ctx);

			var attrName = ctx.GetXamlNsName("Class", elem);

			var attrs = elem.Attributes().ToList();
			if (typeDef.IsNotPublic) {
				var classModifierName = ctx.GetXamlNsName("ClassModifier", elem);
				attrs.Insert(0, new XAttribute(classModifierName, ctx.BamlDecompilerOptions.InternalClassModifier));
			}
			attrs.Insert(0, new XAttribute(attrName, type.ResolvedType.ReflectionFullName));
			elem.ReplaceAttributes(attrs);
		}
		bool RewriteElement(XamlContext ctx, XElement parent, XElement elem) {
			var type = parent.Annotation<XamlType>();
			var property = elem.Annotation<XamlProperty>();
			if ((property == null || type == null) && elem.Name != key)
				return false;

			if (elem.Elements().Count() != 1 || elem.Attributes().Any(t => t.Name.Namespace != XNamespace.Xmlns))
				return false;

			var value = elem.Elements().Single();

			if (!CanInlineExt(ctx, value))
				return false;

			var ext = InlineExtension(ctx, value);
			if (ext == null)
				return false;

			ctx.CancellationToken.ThrowIfCancellationRequested();

			var extValue = ext.ToString(ctx, parent);

			var attrName = elem.Name;
			if (attrName != key)
				attrName = property.ToXName(ctx, parent, property.IsAttachedTo(type));
			var attr = new XAttribute(attrName, extValue);
			parent.Add(attr);
			elem.Remove();

			return true;
		}
示例#5
0
		public void ResolveNamespace(XElement elem, XamlContext ctx) {
			if (Namespace != null)
				return;

			// Since XmlnsProperty records are inside the element,
			// the namespace is resolved after processing the element body.

			string xmlNs = null;
			if (elem.Annotation<XmlnsScope>() != null)
				xmlNs = elem.Annotation<XmlnsScope>().LookupXmlns(Assembly, TypeNamespace);
			if (xmlNs == null)
				xmlNs = ctx.XmlNs.LookupXmlns(Assembly, TypeNamespace);
			// Sometimes there's no reference to System.Xaml even if x:Type is used
			if (xmlNs == null)
				xmlNs = ctx.TryGetXmlNamespace(Assembly, TypeNamespace);

			if (xmlNs == null) {
				if (AssemblyNameComparer.CompareAll.Equals(Assembly, ctx.Module.Assembly))
					xmlNs = $"clr-namespace:{TypeNamespace}";
				else
					xmlNs = $"clr-namespace:{TypeNamespace};assembly={Assembly.Name}";

				var nsSeg = TypeNamespace.Split('.');	
				var prefix = nsSeg[nsSeg.Length - 1].ToLowerInvariant();
				if (string.IsNullOrEmpty(prefix)) {
					if (string.IsNullOrEmpty(TypeNamespace))
						prefix = "global";
					else
						prefix = "empty";
				}
				int count = 0;
				var truePrefix = prefix;
				XNamespace prefixNs, ns = ctx.GetXmlNamespace(xmlNs);
				while ((prefixNs = elem.GetNamespaceOfPrefix(truePrefix)) != null && prefixNs != ns) {
					count++;
					truePrefix = prefix + count;
				}

				if (prefixNs == null) {
					elem.Add(new XAttribute(XNamespace.Xmlns + XmlConvert.EncodeLocalName(truePrefix), ns));
					if (string.IsNullOrEmpty(TypeNamespace))
						elem.AddBeforeSelf(new XComment(string.Format(dnSpy_BamlDecompiler_Resources.Msg_GlobalNamespace, truePrefix)));
				}
			}
			Namespace = ctx.GetXmlNamespace(xmlNs);
		}
示例#6
0
        /// <summary>
        /// Adds UVML annotations to the specified UVML element tree.
        /// </summary>
        /// <param name="dataSourceTypeName">The name of the data source wrapper associated with this tree.</param>
        /// <param name="root">The root of the UVML element tree to annotate.</param>
        public static void AddUvmlAnnotations(String dataSourceTypeName, XElement root)
        {
            Contract.RequireNotEmpty(dataSourceTypeName, nameof(dataSourceTypeName));
            Contract.Require(root, nameof(root));

            var templates = 0;

            if (root.Annotation<UvmlMetadataAnnotation>() != null)
                return;

            root.AddAnnotation(new UvmlMetadataAnnotation());
            AddUvmlAnnotations(dataSourceTypeName, root, ref templates);
        }
 private static void RemoveAllButSpecificFields(XElement root, string[] fieldTypesToRetain)
 {
     var cachedAnnotationInformation = root.Annotation<Dictionary<int, List<XElement>>>();
     List<XElement> runsToKeep = new List<XElement>();
     foreach (var item in cachedAnnotationInformation)
     {
         var runsForField = root
             .Descendants()
             .Where(d =>
             {
                 Stack<FieldRetriever.FieldElementTypeInfo> stack = d.Annotation<Stack<FieldRetriever.FieldElementTypeInfo>>();
                 if (stack == null)
                     return false;
                 if (stack.Any(stackItem => stackItem.Id == item.Key))
                     return true;
                 return false;
             })
             .Select(d => d.AncestorsAndSelf(W.r).FirstOrDefault())
             .GroupAdjacent(o => o)
             .Select(g => g.First())
             .ToList();
         foreach (var r in runsForField)
             runsToKeep.Add(r);
     }
     foreach (var paragraph in root.Descendants(W.p).ToList())
     {
         if (paragraph.Elements(W.r).Any(r => runsToKeep.Contains(r)))
         {
             paragraph.Elements(W.r)
                 .Where(r => !runsToKeep.Contains(r) &&
                     !r.Elements(W.tab).Any())
                 .Remove();
             paragraph.Elements(W.r)
                 .Where(r => !runsToKeep.Contains(r))
                 .Elements()
                 .Where(rc => rc.Name != W.rPr &&
                     rc.Name != W.tab)
                 .Remove();
         }
         else
         {
             paragraph.Remove();
         }
     }
     root.Descendants(W.tbl).Remove();
 }
示例#8
0
		bool RewriteElement(XamlContext ctx, XElement parent, XElement elem) {
			var property = elem.Annotation<XamlProperty>();
			if (property == null && elem.Name != key)
				return false;

			if (elem.HasAttributes || elem.HasElements)
				return false;

			ctx.CancellationToken.ThrowIfCancellationRequested();

			var value = elem.Value;
			var attrName = elem.Name;
			if (attrName != key)
				attrName = property.ToXName(ctx, parent, property.IsAttachedTo(parent.Annotation<XamlType>()));
			var attr = new XAttribute(attrName, value);
			parent.Add(attr);
			elem.Remove();

			return true;
		}
示例#9
0
        private static LineInfo GetLineInfo(XElement element) {
            IXmlLineInfo ie = (IXmlLineInfo) element;

            if(ie.HasLineInfo())
                return new LineInfo(ie.LineNumber, ie.LinePosition);
            else
                return element.Annotation<ABB.SrcML.LineInfo>();
        }
 /// Accept deleted paragraphs.
 ///
 /// Group together all paragraphs that contain w:p/w:pPr/w:rPr/w:del elements.  Make a
 /// second group for the content element immediately following a paragraph that contains
 /// a w:del element.  The code uses the approach of dealing with paragraph content at
 /// 'levels', ignoring paragraph content at other levels.  Form a new paragraph that
 /// contains the content of the grouped paragraphs with deleted paragraph marks, and the
 /// content of the paragraph immediately following a paragraph that contains a deleted
 /// paragraph mark.  Include in the new paragraph the paragraph properties from the
 /// paragraph following.  When assembling the new paragraph, use a transform that collapses
 /// the paragraph nodes when adding content, thereby preserving custom XML and content
 /// controls.
 private static void AnnotateBlockContentElements(XElement contentContainer)
 {
     // For convenience, there is a ParagraphInfo annotation on the contentContainer.
     // It contains the same information as the ParagraphInfo annotation on the first
     //   paragraph.
     if (contentContainer.Annotation<BlockContentInfo>() != null)
         return;
     XElement firstContentElement = contentContainer
         .Elements()
         .DescendantsAndSelf()
         .FirstOrDefault(e => e.Name == W.p || e.Name == W.tbl);
     // Add the annotation on the contentContainer.
     BlockContentInfo currentContentInfo = new BlockContentInfo()
     {
         PreviousBlockContentElement = null,
         ThisBlockContentElement = firstContentElement,
         NextBlockContentElement = null
     };
     // Add as annotation even though NextParagraph is not set yet.
     contentContainer.AddAnnotation(currentContentInfo);
     while (true)
     {
         currentContentInfo.ThisBlockContentElement.AddAnnotation(currentContentInfo);
         // Find next sibling content element.
         XElement nextContentElement = null;
         XElement current = currentContentInfo.ThisBlockContentElement;
         while (true)
         {
             nextContentElement = current
                 .ElementsAfterSelf()
                 .DescendantsAndSelf()
                 .FirstOrDefault(e => e.Name == W.p || e.Name == W.tbl);
             if (nextContentElement != null)
             {
                 currentContentInfo.NextBlockContentElement = nextContentElement;
                 break;
             }
             current = current.Parent;
             // When we've backed up the tree to the contentContainer, we're done.
             if (current == contentContainer)
                 return;
         }
         currentContentInfo = new BlockContentInfo()
         {
             PreviousBlockContentElement = currentContentInfo.ThisBlockContentElement,
             ThisBlockContentElement = nextContentElement,
             NextBlockContentElement = null
         };
     }
 }
 private static IEnumerable<BlockContentInfo> IterateBlockContentElements(XElement element)
 {
     XElement current = element.Elements().FirstOrDefault();
     if (current == null)
         yield break;
     AnnotateBlockContentElements(element);
     BlockContentInfo currentBlockContentInfo = element.Annotation<BlockContentInfo>();
     while (true)
     {
         yield return currentBlockContentInfo;
         if (currentBlockContentInfo.NextBlockContentElement == null)
             yield break;
         currentBlockContentInfo = currentBlockContentInfo.NextBlockContentElement.Annotation<BlockContentInfo>();
     }
 }
		bool CanInlineExt(XamlContext ctx, XElement ctxElement) {
			var type = ctxElement.Annotation<XamlType>();
			if (type != null && type.ResolvedType != null) {
				var typeDef = type.ResolvedType.GetBaseType();
				bool isExt = false;
				while (typeDef != null) {
					if (typeDef.FullName == "System.Windows.Markup.MarkupExtension") {
						isExt = true;
						break;
					}
					typeDef = typeDef.GetBaseType();
				}
				if (!isExt)
					return false;
			}
			else if (ctxElement.Annotation<XamlProperty>() == null &&
			         ctxElement.Name != ctor)
				return false;

			foreach (var child in ctxElement.Elements()) {
				if (!CanInlineExt(ctx, child))
					return false;
			}
			return true;
		}
            private Location GetIncludeElementLocation(XElement includeElement, ref string currentXmlFilePath, ref CSharpSyntaxNode originatingSyntax)
            {
                Location location = includeElement.Annotation<Location>();
                if (location != null)
                {
                    return location;
                }

                // If we are not in an XML file, then we must be in a source file.  Since we're traversing the XML tree in the same
                // order as the DocumentationCommentWalker, we can access the elements of includeElementNodes in order.
                if (currentXmlFilePath == null)
                {
                    Debug.Assert(nextSourceIncludeElementIndex < sourceIncludeElementNodes.Length);
                    Debug.Assert(originatingSyntax == null);
                    originatingSyntax = sourceIncludeElementNodes[nextSourceIncludeElementIndex];
                    location = originatingSyntax.Location;
                    nextSourceIncludeElementIndex++;

                    // #line shall not affect the base path:
                    currentXmlFilePath = location.GetLineSpan().Path;
                }
                else
                {
                    location = XmlLocation.Create(includeElement, currentXmlFilePath);
                }

                Debug.Assert(location != null);
                includeElement.AddAnnotation(location);
                return location;
            }
        public static string RetrieveListItem(WordprocessingDocument wordDoc, XElement paragraph, ListItemRetrieverSettings settings)
        {
            if (wordDoc.MainDocumentPart.NumberingDefinitionsPart == null)
                return null;

            var listItemInfo = paragraph.Annotation<ListItemInfo>();
            if (listItemInfo == null)
                InitializeListItemRetriever(wordDoc, settings);

            listItemInfo = paragraph.Annotation<ListItemInfo>();
            if (!listItemInfo.IsListItem)
                return null;

            var numberingDefinitionsPart = wordDoc
                .MainDocumentPart
                .NumberingDefinitionsPart;

            if (numberingDefinitionsPart == null)
                return null;

            StyleDefinitionsPart styleDefinitionsPart = wordDoc
                .MainDocumentPart
                .StyleDefinitionsPart;

            if (styleDefinitionsPart == null)
                return null;

            var numXDoc = numberingDefinitionsPart.GetXDocument();
            var stylesXDoc = styleDefinitionsPart.GetXDocument();

            var lvl = listItemInfo.Lvl(GetParagraphLevel(paragraph));

            string lvlText = (string)lvl.Elements(W.lvlText).Attributes(W.val).FirstOrDefault();
            if (lvlText == null)
                return null;

            var levelNumbersAnnotation = paragraph.Annotation<LevelNumbers>();
            if (levelNumbersAnnotation == null)
                throw new OpenXmlPowerToolsException("Internal error");

            int[] levelNumbers = levelNumbersAnnotation.LevelNumbersArray;
            string languageIdentifier = GetLanguageIdentifier(paragraph, stylesXDoc);
            string listItem = FormatListItem(listItemInfo, levelNumbers, GetParagraphLevel(paragraph), 
                lvlText, stylesXDoc, languageIdentifier, settings);
            return listItem;
        }
 public static int GetParagraphLevel(XElement paragraph)
 {
     var pi = paragraph.Annotation<ParagraphInfo>();
     if (pi != null)
         return pi.Ilvl;
     throw new OpenXmlPowerToolsException("Internal error - should never ask for ilvl without it first being set.");
 }
        private static void AnnotateParagraph(FormattingAssemblerInfo fai, WordprocessingDocument wDoc, XElement para, FormattingAssemblerSettings settings)
        {
            XElement localParaProps = para.Element(W.pPr);
            if (localParaProps == null)
            {
                localParaProps = new XElement(W.pPr);
            }

            // get para table props, to be merged.
            XElement tablepPr = null;

            var blockLevelContentContainer = para
                .Ancestors()
                .FirstOrDefault(a => a.Name == W.body ||
                    a.Name == W.tbl ||
                    a.Name == W.txbxContent ||
                    a.Name == W.ftr ||
                    a.Name == W.hdr ||
                    a.Name == W.footnote ||
                    a.Name == W.endnote);
            if (blockLevelContentContainer.Name == W.tbl)
            {
                XElement tbl = blockLevelContentContainer;
                XElement style = tbl.Element(PtOpenXml.pt + "style");
                XElement cellCnf = para.Ancestors(W.tc).Take(1).Elements(W.tcPr).Elements(W.cnfStyle).FirstOrDefault();
                XElement rowCnf = para.Ancestors(W.tr).Take(1).Elements(W.trPr).Elements(W.cnfStyle).FirstOrDefault();

                if (style != null)
                {
                    // roll up tblPr, trPr, and tcPr from within a specific style.
                    // add each of these to the table, in PowerTools namespace.
                    tablepPr = style.Element(W.pPr);
                    if (tablepPr == null)
                        tablepPr = new XElement(W.pPr);

                    foreach (var ot in TableStyleOverrideTypes)
                    {
                        XName attName = TableStyleOverrideXNameMap[ot];
                        if ((cellCnf != null && cellCnf.Attribute(attName).ToBoolean() == true) ||
                            (rowCnf != null && rowCnf.Attribute(attName).ToBoolean() == true))
                        {
                            XElement o = style
                                .Elements(W.tblStylePr)
                                .Where(tsp => (string)tsp.Attribute(W.type) == ot)
                                .FirstOrDefault();
                            if (o != null)
                            {
                                XElement otpPr = o.Element(W.pPr);
                                tablepPr = MergeStyleElement(otpPr, tablepPr);
                            }
                        }
                    }
                }
            }
            var stylesPart = wDoc.MainDocumentPart.StyleDefinitionsPart;
            XDocument sXDoc = null;
            if (stylesPart != null)
                sXDoc = stylesPart.GetXDocument();

            ListItemRetriever.ListItemInfo lif = para.Annotation<ListItemRetriever.ListItemInfo>();

            XElement rolledParaProps = ParagraphStyleRollup(para, sXDoc, fai.DefaultParagraphStyleName);
            if (lif != null && lif.IsZeroNumId)
                rolledParaProps.Elements(W.ind).Remove();
            XElement toggledParaProps = MergeStyleElement(rolledParaProps, tablepPr);
            XElement mergedParaProps = MergeStyleElement(localParaProps, toggledParaProps);

            string li = ListItemRetriever.RetrieveListItem(wDoc, para, settings.ListItemRetrieverSettings);
            if (lif != null && lif.IsListItem)
            {
                if (settings.RestrictToSupportedNumberingFormats)
                {
                    string numFmtForLevel = (string)lif.Lvl(ListItemRetriever.GetParagraphLevel(para)).Elements(W.numFmt).Attributes(W.val).FirstOrDefault();
                    if (numFmtForLevel == null)
                    {
                        var numFmtElement = lif.Lvl(ListItemRetriever.GetParagraphLevel(para)).Elements(MC.AlternateContent).Elements(MC.Choice).Elements(W.numFmt).FirstOrDefault();
                        if (numFmtElement != null && (string)numFmtElement.Attribute(W.val) == "custom")
                            numFmtForLevel = (string)numFmtElement.Attribute(W.format);
                    }
                    bool isLgl = lif.Lvl(ListItemRetriever.GetParagraphLevel(para)).Elements(W.isLgl).Any();
                    if (isLgl && numFmtForLevel != "decimalZero")
                        numFmtForLevel = "decimal";
                    if (!AcceptableNumFormats.Contains(numFmtForLevel))
                        throw new UnsupportedNumberingFormatException(numFmtForLevel + " is not a supported numbering format");
                }

                int paragraphLevel = ListItemRetriever.GetParagraphLevel(para);
                var numberingParaProps = lif
                    .Lvl(paragraphLevel)
                    .Elements(W.pPr)
                    .FirstOrDefault();
                if (numberingParaProps == null)
                {
                    numberingParaProps = new XElement(W.pPr);
                }
                else
                {
                    numberingParaProps
                        .Elements()
                        .Where(e => e.Name != W.ind)
                        .Remove();
                }

                // have:
                // - localParaProps
                // - toggledParaProps
                // - numberingParaProps

                // if a paragraph contains a numPr with a numId=0, in other words, it is NOT a numbered item, then the indentation from the style
                // hierarchy is ignored.

                ListItemRetriever.ListItemInfo lii = para.Annotation<ListItemRetriever.ListItemInfo>();
                if (lii.FromParagraph != null)
                {
                    // order
                    // - toggledParaProps
                    // - numberingParaProps
                    // - localParaProps

                    mergedParaProps = MergeStyleElement(numberingParaProps, toggledParaProps);
                    mergedParaProps = MergeStyleElement(localParaProps, mergedParaProps);
                }
                else if (lii.FromStyle != null)
                {
                    // order
                    // - numberingParaProps
                    // - toggledParaProps
                    // - localParaProps
                    mergedParaProps = MergeStyleElement(toggledParaProps, numberingParaProps);
                    mergedParaProps = MergeStyleElement(localParaProps, mergedParaProps);
                }
            }
            else
            {
                mergedParaProps = MergeStyleElement(localParaProps, toggledParaProps);
            }

            // merge mergedParaProps with existing accumulatedParaProps, with mergedParaProps as high pri
            // replace accumulatedParaProps with newly merged

            XElement accumulatedParaProps = para.Element(PtOpenXml.pt + "pPr");
            XElement newAccumulatedParaProps = MergeStyleElement(mergedParaProps, accumulatedParaProps);

            AdjustFontAttributes(wDoc, para, newAccumulatedParaProps, newAccumulatedParaProps.Element(W.rPr), settings);
            newAccumulatedParaProps.Name = PtOpenXml.pt + "pPr";
            if (accumulatedParaProps != null)
            {
                accumulatedParaProps.ReplaceWith(newAccumulatedParaProps);
            }
            else
            {
                para.Add(newAccumulatedParaProps);
            }
        }
        private static XElement CharStyleRollup(FormattingAssemblerInfo fai, WordprocessingDocument wDoc, XElement runOrPara)
        {
            var sXDoc = wDoc.MainDocumentPart.StyleDefinitionsPart.GetXDocument();

            string charStyle = null;
            string paraStyle = null;
            XElement rPr = null;
            XElement pPr = null;
            XElement pStyle = null;
            XElement rStyle = null;
            CachedParaInfo cpi = null; // CachedParaInfo is an optimization for the case where a paragraph contains thousands of runs.

            if (runOrPara.Name == W.p)
            {
                cpi = runOrPara.Annotation<CachedParaInfo>();
                if (cpi != null)
                    pPr = cpi.ParagraphProperties;
                else
                {
                    pPr = runOrPara.Element(W.pPr);
                    if (pPr != null)
                    {
                        paraStyle = (string)pPr.Elements(W.pStyle).Attributes(W.val).FirstOrDefault();
                    }
                    else
                    {
                        paraStyle = fai.DefaultParagraphStyleName;
                    }
                    cpi = new CachedParaInfo
                    {
                        ParagraphProperties = pPr,
                        ParagraphStyleName = paraStyle,
                    };
                    runOrPara.AddAnnotation(cpi);
                }
                if (pPr != null)
                {
                    rPr = pPr.Element(W.rPr);
                }
            }
            else
            {
                rPr = runOrPara.Element(W.rPr);
            }
            if (rPr != null)
            {
                rStyle = rPr.Element(W.rStyle);
                if (rStyle != null)
                {
                    charStyle = (string)rStyle.Attribute(W.val);
                }
                else
                {
                    if (runOrPara.Name == W.r)
                        charStyle = (string)runOrPara
                            .Ancestors(W.p)
                            .Take(1)
                            .Elements(W.pPr)
                            .Elements(W.pStyle)
                            .Attributes(W.val)
                            .FirstOrDefault();
                    else
                        charStyle = (string)runOrPara
                            .Elements(W.pPr)
                            .Elements(W.pStyle)
                            .Attributes(W.val)
                            .FirstOrDefault();
                }
            }

            if (charStyle == null)
            {
                if (runOrPara.Name == W.r)
                {
                    var ancestorPara = runOrPara.Ancestors(W.p).First();
                    cpi = ancestorPara.Annotation<CachedParaInfo>();
                    if (cpi != null)
                        charStyle = cpi.ParagraphStyleName;
                    else
                        charStyle = (string)runOrPara.Ancestors(W.p).First().Elements(W.pPr).Elements(W.pStyle).Attributes(W.val).FirstOrDefault();
                }
                if (charStyle == null)
                {
                    charStyle = fai.DefaultParagraphStyleName;
                }
            }

            // A run always must have an ancestor paragraph.
            XElement para = null;
            var rolledUpParaStyleRunProps = new XElement(W.rPr);
            if (runOrPara.Name == W.r)
            {
                para = runOrPara.Ancestors(W.p).FirstOrDefault();
            }
            else
            {
                para = runOrPara;
            }

            cpi = para.Annotation<CachedParaInfo>();
            if (cpi != null)
            {
                pPr = cpi.ParagraphProperties;
            }
            else
            {
                pPr = para.Element(W.pPr);
            }
            if (pPr != null)
            {
                pStyle = pPr.Element(W.pStyle);
                if (pStyle != null)
                {
                    paraStyle = (string)pStyle.Attribute(W.val);
                }
                else
                {
                    paraStyle = fai.DefaultParagraphStyleName;
                }
            }
            else
                paraStyle = fai.DefaultParagraphStyleName;

            string key = (paraStyle == null ? "[null]" : paraStyle) + "~|~" +
                (charStyle == null ? "[null]" : charStyle);
            XElement rolledRunProps = null;

            if (fai.RolledCharacterStyles.ContainsKey(key))
                rolledRunProps = fai.RolledCharacterStyles[key];
            else
            {
                XElement rolledUpCharStyleRunProps = new XElement(W.rPr);
                if (charStyle != null)
                {
                    rolledUpCharStyleRunProps =
                        CharStyleStack(wDoc, charStyle)
                            .Aggregate(new XElement(W.rPr),
                                (r, s) =>
                                {
                                    var newRunProps = MergeStyleElement(s, r);
                                    return newRunProps;
                                });
                }

                if (paraStyle != null)
                {
                    rolledUpParaStyleRunProps = ParaStyleRunPropsStack(wDoc, paraStyle)
                        .Aggregate(new XElement(W.rPr),
                            (r, s) =>
                            {
                                var newCharStyleRunProps = MergeStyleElement(s, r);
                                return newCharStyleRunProps;
                            });
                }
                rolledRunProps = MergeStyleElement(rolledUpCharStyleRunProps, rolledUpParaStyleRunProps);
                fai.RolledCharacterStyles.Add(key, rolledRunProps);
            }

            return rolledRunProps;
        }
        public static string InstrText(XElement root, int id)
        {

            XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

#if false
            // This is the old code.  Both versions work - the caching version is significantly faster.
            var relevantElements = root.Descendants()
                .Where(e =>
                {
                    Stack<FieldElementTypeInfo> s = e.Annotation<Stack<FieldElementTypeInfo>>();
                    if (s != null)
                        return s.Any(z => z.Id == id &&
                            z.FieldElementType == FieldElementTypeEnum.InstrText);
                    return false;
                })
                .ToList();
#else
            var cachedAnnotationInformation = root.Annotation<Dictionary<int, List<XElement>>>();
            if (cachedAnnotationInformation == null)
                throw new OpenXmlPowerToolsException("Internal error");

            // it is possible that a field code contains no instr text
            if (!cachedAnnotationInformation.ContainsKey(id))
                return "";
            var relevantElements = cachedAnnotationInformation[id];
#endif

            var groupedSubFields = relevantElements
                .GroupAdjacent(e =>
                {
                    Stack<FieldElementTypeInfo> s = e.Annotation<Stack<FieldElementTypeInfo>>();
                    var stackElement = s.FirstOrDefault(z => z.Id == id);
                    var elementsBefore = s.TakeWhile(z => z != stackElement);
                    return elementsBefore.Any();
                })
                .ToList();

            var instrText = groupedSubFields
                .Select(g =>
                {
                    if (g.Key == false)
                    {
                        return g.Select(e =>
                        {
                            Stack<FieldElementTypeInfo> s = e.Annotation<Stack<FieldElementTypeInfo>>();
                            var stackElement = s.FirstOrDefault(z => z.Id == id);
                            if (stackElement.FieldElementType == FieldElementTypeEnum.InstrText &&
                                e.Name == w + "instrText")
                                return e.Value;
                            return "";
                        })
                            .StringConcatenate();
                    }
                    else
                    {
                        Stack<FieldElementTypeInfo> s = g.First().Annotation<Stack<FieldElementTypeInfo>>();
                        var stackElement = s.FirstOrDefault(z => z.Id == id);
                        var elementBefore = s.TakeWhile(z => z != stackElement).Last();
                        var subFieldId = elementBefore.Id;
                        return InstrText(root, subFieldId);
                    }
                })
                .StringConcatenate();

            return "{" + instrText + "}";
        }
示例#19
0
		/// <summary>
		/// Валидизация исходного XML
		/// </summary>
		/// <param name="srcXml">Элемент для проверки соответствия PHTML</param>
		/// <param name="context">Контекст обработки PHTML (дополнительные настройки, опции, списки доверения)</param>
		/// <returns></returns>
		public static PortableHtmlContext Validate(XElement srcXml, PortableHtmlContext context = null)
		{
			context = context ?? new PortableHtmlContext();
			context.SourceXml = srcXml;
			//hack way to provide addition info to method
			if (null == srcXml.Annotation<CheckedBySourceCheckerAnnotation>()){
				CheckRootElement(context);
				if (!context.IsActive) return context;
				CheckNoComments(context);
				if (!context.IsActive) return context;
				CheckNoProcessingInstructions(context);
				if (!context.IsActive) return context;
			}

			CheckDeprecatedElements(context);
			if (!context.IsActive) return context;
			CheckNamespaces(context);
			if (!context.IsActive) return context;
			CheckDeprecatedAttributes(context);
			if (!context.IsActive) return context;
			CheckUpperCase(context);
			if (!context.IsActive) return context;
			CheckEmptyElements(context);
			if (!context.IsActive) return context;
			CheckAnchorLinks(context);
			if (!context.IsActive) return context;
			CheckImageLinks(context);
			if (!context.IsActive) return context;
			CheckRootTextNodes(context);
			if (!context.IsActive) return context;
			CheckRootInlineElements(context);
			if (!context.IsActive) return context;
			CheckNestedParas(context);
			if (!context.IsActive) return context;
			CheckNoTextElementsText(context);
			if (!context.IsActive) return context;
			CheckNoTextElementsInlines(context);
			if (!context.IsActive) return context;
			if (context.Level.HasFlag(PortableHtmlStrictLevel.AllowBr)){
				CheckBrPosition(context);
				if (!context.IsActive) return context;
			}
			if (context.Level.HasFlag(PortableHtmlStrictLevel.AllowLists))
			{
				CheckListSchema(context);
				if (!context.IsActive) return context;
			}
			if (context.Level.HasFlag(PortableHtmlStrictLevel.AllowTables))
			{
				CheckTableSchema(context);
				if (!context.IsActive) return context;
			}
			return context;
		}
示例#20
0
                /// <summary>
                /// Validate the behavior of annotations on Container.
                /// </summary>
                /// <param name="contextValue"></param>
                /// <returns></returns>
                //[Variation(Desc = "ContainerAnnotations")]
                public void ContainerAnnotations()
                {
                    XElement element1 = new XElement("e1");
                    XElement element2 = new XElement("e2");

                    // Check argument null exception on add.
                    try
                    {
                        element1.AddAnnotation(null);
                        Validate.ExpectedThrow(typeof(ArgumentNullException));
                    }
                    catch (Exception ex)
                    {
                        Validate.Catch(ex, typeof(ArgumentNullException));
                    }

                    // Before adding anything, should not be able to get any annotations.
                    Validate.IsNull(element1.Annotation(typeof(object)));
                    element1.RemoveAnnotations(typeof(object));
                    Validate.IsNull(element1.Annotation(typeof(object)));

                    // First annotation: 2 cases, object[] and other.
                    object obj1 = "hello";
                    element1.AddAnnotation(obj1);
                    Validate.IsNull(element1.Annotation(typeof(byte)));
                    Validate.IsReferenceEqual(element1.Annotation(typeof(string)), obj1);
                    element1.RemoveAnnotations(typeof(string));
                    Validate.IsNull(element1.Annotation(typeof(string)));

                    object[] obj2 = new object[] { 10, 20, 30 };

                    element2.AddAnnotation(obj2);
                    Validate.IsReferenceEqual(element2.Annotation(typeof(object[])), obj2);
                    Validate.Enumerator<object>((object[])element2.Annotation(typeof(object[])), new object[] { 10, 20, 30 });
                    element2.RemoveAnnotations(typeof(object[]));
                    Validate.IsNull(element2.Annotation(typeof(object[])));

                    // Single annotation; add a second one. Check that duplicates are allowed.
                    object obj3 = 10;
                    element1.AddAnnotation(obj3);
                    Validate.IsReferenceEqual(element1.Annotation(typeof(int)), obj3);
                    element1.AddAnnotation(1000);
                    element1.RemoveAnnotations(typeof(int[]));
                    Validate.IsNull(element1.Annotation(typeof(object[])));

                    object obj4 = "world";
                    element1.AddAnnotation(obj4);

                    Validate.IsReferenceEqual(element1.Annotation(typeof(int)), obj3);
                    Validate.IsReferenceEqual(element1.Annotation(typeof(string)), obj4);

                    // Multiple annotations already. Add one on the end.
                    object obj5 = 20L;
                    element1.AddAnnotation(obj5);

                    Validate.IsReferenceEqual(element1.Annotation(typeof(int)), obj3);
                    Validate.IsReferenceEqual(element1.Annotation(typeof(string)), obj4);
                    Validate.IsReferenceEqual(element1.Annotation(typeof(long)), obj5);

                    // Remove one from the middle and then add, which should use the
                    // freed slot.
                    element1.RemoveAnnotations(typeof(string));
                    Validate.IsNull(element1.Annotation(typeof(string)));

                    object obj6 = 30m;
                    element1.AddAnnotation(obj6);

                    Validate.IsReferenceEqual(element1.Annotation(typeof(int)), obj3);
                    Validate.IsReferenceEqual(element1.Annotation(typeof(long)), obj5);
                    Validate.IsReferenceEqual(element1.Annotation(typeof(decimal)), obj6);

                    // Ensure that duplicates are allowed.           
                    element1.AddAnnotation(40m);
                    Validate.IsNull(element1.Annotation(typeof(sbyte)));

                    // A couple of additional remove cases.
                    element2.AddAnnotation(obj2);
                    element2.AddAnnotation(obj3);
                    element2.AddAnnotation(obj5);
                    element2.AddAnnotation(obj6);

                    element2.RemoveAnnotations(typeof(float));
                    Validate.IsNull(element2.Annotation(typeof(float)));
                }
 public static ListItemInfo GetListItemInfo(XDocument numXDoc, XDocument stylesXDoc, XElement paragraph)
 {
     // The following is an optimization - only determine ListItemInfo once for a
     // paragraph.
     ListItemInfo listItemInfo = paragraph.Annotation<ListItemInfo>();
     if (listItemInfo != null)
         return listItemInfo;
     throw new OpenXmlPowerToolsException("Attempting to retrieve ListItemInfo before initialization");
 }
示例#22
0
                //[Variation(Desc = "Tuple - New Dev10 Types", Param = 1)]
                //[Variation(Desc = "DynamicObject - New Dev10 Types", Param = 2)]
                //[Variation(Desc = "Guid - old type", Param = 3)]
                //[Variation(Desc = "Dictionary - old type", Param = 4)]
                public void CreatingXElementsFromNewDev10Types()
                {
                    object t = null;
                    Type type = typeof(object);
                    int param = (int)this.Variation.Param;
                    switch (param)
                    {
                        case 1: t = Tuple.Create(1, "Melitta", 7.5); type = typeof(Tuple); break;
                        case 3: t = new Guid(); type = typeof(Guid); break;
                        case 4: t = new Dictionary<int, string>(); ((Dictionary<int, string>)t).Add(7, "a"); type = typeof(Dictionary<int, string>); break;
                    }

                    XElement e = new XElement("e1",
                        new XElement("e2"), "text1",
                        new XElement("e3"), t);
                    e.Add(t);
                    e.FirstNode.ReplaceWith(t);

                    XNode n = e.FirstNode.NextNode;
                    n.AddBeforeSelf(t);
                    n.AddAnnotation(t);
                    n.ReplaceWith(t);

                    e.FirstNode.AddAfterSelf(t);
                    e.AddFirst(t);
                    e.Annotation(type);
                    e.Annotations(type);
                    e.RemoveAnnotations(type);
                    e.ReplaceAll(t);
                    e.ReplaceAttributes(t);
                    e.ReplaceNodes(t);
                    e.SetAttributeValue("a", t);
                    e.SetElementValue("e2", t);
                    e.SetValue(t);

                    XAttribute a = new XAttribute("a", t);
                    XStreamingElement se = new XStreamingElement("se", t);
                    se.Add(t);

                    try
                    {
                        new XDocument(t);
                    }
                    catch (ArgumentException)
                    {
                        try
                        {
                            new XDocument(t);
                        }
                        catch (ArgumentException)
                        {
                            return;
                        }
                    }
                    TestLog.Compare(false, "Failed");
                }
示例#23
0
		void CheckConnectionId(XamlContext ctx, XElement elem, Dictionary<int, Action<XamlContext, XElement>> connIds) {
			var connId = elem.Annotation<BamlConnectionId>();
			if (connId == null)
				return;

			Action<XamlContext, XElement> cb;
			if (!connIds.TryGetValue((int)connId.Id, out cb)) {
				elem.AddBeforeSelf(new XComment("Unknown connection ID: " + connId.Id));
				return;
			}

			cb(ctx, elem);
		}
示例#24
0
        /// <summary>
        /// Searches the specified XML tree for any elements which are annotated as framework templates.
        /// </summary>
        private static void GetFrameworkTemplateElements(XElement root, IDictionary<String, XElement> elements)
        {
            var annotation = root.Annotation<FrameworkTemplateNameAnnotation>();
            if (annotation != null)
                elements[annotation.Name] = root;

            var children = root.Elements();
            foreach (var child in children)
                GetFrameworkTemplateElements(child, elements);
        }
 public static void SetParagraphLevel(XElement paragraph, int ilvl)
 {
     var pi = paragraph.Annotation<ParagraphInfo>();
     if (pi == null)
     {
         pi = new ParagraphInfo()
         {
             Ilvl = ilvl,
         };
         paragraph.AddAnnotation(pi);
         return;
     }
     throw new OpenXmlPowerToolsException("Internal error - should never set ilvl more than once.");
 }
示例#26
0
		/// <summary>
		/// </summary>
		/// <param name="el"></param>
		/// <returns></returns>
		public bool InChecking(XElement el){
			if (Strategy == PortableHtmlVerificationStrategy.Full) return true;
			return null == el.Annotation<SkipInElementChecking>();
		}
        private static IEnumerable<XElement> ParaStyleParaPropsStack(XDocument stylesXDoc, string paraStyleName, XElement para)
        {
            if (stylesXDoc == null)
                yield break;
            var localParaStyleName = paraStyleName;
            while (localParaStyleName != null)
            {
                XElement paraStyle = stylesXDoc.Root.Elements(W.style).FirstOrDefault(s =>
                    s.Attribute(W.type).Value == "paragraph" &&
                    s.Attribute(W.styleId).Value == localParaStyleName);
                if (paraStyle == null)
                {
                    yield break;
                }
                if (paraStyle.Element(W.pPr) == null)
                {
                    if (paraStyle.Element(W.rPr) != null)
                    {
                        var elementToYield2 = new XElement(W.pPr,
                            paraStyle.Element(W.rPr));
                        yield return elementToYield2;
                    }
                    localParaStyleName = (string)(paraStyle
                        .Elements(W.basedOn)
                        .Attributes(W.val)
                        .FirstOrDefault());
                    continue;
                }

                var elementToYield = new XElement(W.pPr,
                    paraStyle.Element(W.pPr).Attributes(),
                    paraStyle.Element(W.pPr).Elements(),
                    paraStyle.Element(W.rPr));
                yield return (elementToYield);

                var listItemInfo = para.Annotation<ListItemRetriever.ListItemInfo>();
                if (listItemInfo != null)
                {
                    if (listItemInfo.IsListItem)
                    {
                        XElement lipPr = listItemInfo.Lvl(ListItemRetriever.GetParagraphLevel(para)).Element(W.pPr);
                        if (lipPr == null)
                            lipPr = new XElement(W.pPr);
                        XElement lirPr = listItemInfo.Lvl(ListItemRetriever.GetParagraphLevel(para)).Element(W.rPr);
                        var elementToYield2 = new XElement(W.pPr,
                            lipPr.Attributes(),
                            lipPr.Elements(),
                            lirPr);
                        yield return (elementToYield2);
                    }
                }

                localParaStyleName = (string)paraStyle
                    .Elements(W.basedOn)
                    .Attributes(W.val)
                    .FirstOrDefault();
            }
            yield break;
        }
示例#28
0
		void CheckConnectionId(XamlContext ctx, XElement elem, Dictionary<int, Action<XamlContext, XElement>> connIds) {
			var connId = elem.Annotation<BamlConnectionId>();
			if (connId == null)
				return;

			Action<XamlContext, XElement> cb;
			if (!connIds.TryGetValue((int)connId.Id, out cb)) {
				elem.AddBeforeSelf(new XComment(string.Format(dnSpy_BamlDecompiler_Resources.Error_UnknownConnectionId, connId.Id)));
				return;
			}

			cb(ctx, elem);
		}
		XamlExtension InlineExtension(XamlContext ctx, XElement ctxElement) {
			var type = ctxElement.Annotation<XamlType>();
			if (type == null)
				return null;

			var ext = new XamlExtension(type);

			foreach (var attr in ctxElement.Attributes().Where(attr => attr.Name.Namespace != XNamespace.Xmlns))
				ext.NamedArguments[attr.Name.LocalName] = attr.Value;

			foreach (var child in ctxElement.Nodes()) {
				var elem = child as XElement;
				if (elem == null)
					return null;

				if (elem.Name == ctor) {
					if (ext.Initializer != null)
						return null;

					var args = InlineCtor(ctx, elem);
					if (args == null)
						return null;

					ext.Initializer = args;
					continue;
				}

				var property = elem.Annotation<XamlProperty>();
				if (property == null || elem.Nodes().Count() != 1 ||
				    elem.Attributes().Any(attr => attr.Name.Namespace != XNamespace.Xmlns))
					return null;

				var name = property.PropertyName;
				var value = InlineObject(ctx, elem.Nodes().Single());
				ext.NamedArguments[name] = value;
			}
			return ext;
		}
示例#30
0
        /// <summary>
        /// Searches the specified XML element tree for binding expressions and adds them to the specified collection.
        /// </summary>
        /// <param name="state">The expression compiler's current state.</param>
        /// <param name="dataSourceDefinition">The data source definition for the data source which is being compiled.</param>
        /// <param name="dataSourceWrappedType">The type for which a data source wrapper is being compiled.</param>
        /// <param name="element">The root of the XML element tree to search.</param>
        /// <param name="expressions">The list to populate with any binding expressions that are found.</param>
        private static void FindBindingExpressionsInDataSource(ExpressionCompilerState state, DataSourceDefinition dataSourceDefinition,
            Type dataSourceWrappedType, XElement element, List<BindingExpressionInfo> expressions)
        {
            var templateAnnotation = element.Annotation<FrameworkTemplateNameAnnotation>();
            if (templateAnnotation != null)
                return;

            var elementName = element.Name.LocalName;
            var elementType = GetPlaceholderType(dataSourceWrappedType, elementName);
            if (elementType != null || state.GetKnownType(elementName, out elementType))
            {
                var attrs = element.Attributes();
                foreach (var attr in attrs)
                {
                    var attrValue = attr.Value;
                    if (!BindingExpressions.IsBindingExpression(attrValue))
                        continue;

                    var dprop = FindDependencyOrAttachedPropertyByName(state, attr.Name.LocalName, elementType);
                    if (dprop == null)
                    {
                        throw new BindingExpressionCompilationErrorException(attr, dataSourceDefinition.DefinitionPath,
                            CompilerStrings.OnlyDependencyPropertiesCanBeBound.Format(attr.Name.LocalName));
                    }

                    var expText = BindingExpressions.GetBindingMemberPathPart(attrValue);
                    var expProp = GetBindablePropertyOnDataSource(dataSourceWrappedType, expText);

                    expressions.Add(new BindingExpressionInfo(attr,
                        attrValue, expProp?.PropertyType ?? dprop.PropertyType) { GenerateGetter = true });
                }

                if (element.Nodes().Count() == 1)
                {
                    var singleChild = element.Nodes().Single();
                    if (singleChild.NodeType == XmlNodeType.Text)
                    {
                        var elementValue = ((XText)singleChild).Value;
                        if (BindingExpressions.IsBindingExpression(elementValue))
                        {
                            String defaultProperty;
                            if (!state.GetElementDefaultProperty(elementType, out defaultProperty) || defaultProperty == null)
                            {
                                throw new BindingExpressionCompilationErrorException(singleChild, dataSourceDefinition.DefinitionPath,
                                    CompilerStrings.ElementDoesNotHaveDefaultProperty.Format(elementType.Name));
                            }

                            var dprop = FindDependencyOrAttachedPropertyByName(state, defaultProperty, elementType);
                            if (dprop == null)
                            {
                                throw new BindingExpressionCompilationErrorException(singleChild, dataSourceDefinition.DefinitionPath,
                                    CompilerStrings.OnlyDependencyPropertiesCanBeBound.Format(defaultProperty));
                            }

                            var expText = BindingExpressions.GetBindingMemberPathPart(elementValue);
                            var expProp = GetBindablePropertyOnDataSource(dataSourceWrappedType, expText);

                            expressions.Add(new BindingExpressionInfo(singleChild,
                                elementValue, expProp?.PropertyType ?? dprop.PropertyType) { GenerateGetter = true });
                        }
                    }
                }
            }

            var children = element.Elements();
            foreach (var child in children)
            {
                FindBindingExpressionsInDataSource(state, dataSourceDefinition,
                    dataSourceWrappedType, child, expressions);
            }
        }