예제 #1
0
        internal ResolveResult ResolveElement(AXmlElement element, CancellationToken cancellationToken = default(CancellationToken))
        {
            string namespaceName = element.Namespace;
            string name          = element.LocalName;

            if (name.Contains("."))
            {
                string propertyName = name.Substring(name.IndexOf('.') + 1);
                name = name.Substring(0, name.IndexOf('.'));
                ITypeReference reference  = XamlUnresolvedFile.CreateTypeReference(namespaceName, name);
                IType          type       = reference.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly));
                IMember        member     = FindMember(type, propertyName);
                IMember        underlying = null;
                if (member == null)
                {
                    member = FindAttachedMember(type, propertyName, out underlying);
                }
                if (member == null)
                {
                    return(new UnknownMemberResolveResult(type, propertyName, EmptyList <IType> .Instance));
                }
                if (underlying != null)
                {
                    return(new AttachedMemberResolveResult(new TypeResolveResult(type), underlying, member));
                }
                return(new MemberResolveResult(new TypeResolveResult(type), member));
            }
            else
            {
                ITypeReference reference = XamlUnresolvedFile.CreateTypeReference(namespaceName, name);
                IType          type      = reference.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly));
                return(new TypeResolveResult(type));
            }
        }
 /// <summary> Visit AXmlElement </summary>
 public virtual void VisitElement(AXmlElement element)
 {
     foreach (AXmlObject child in element.Children)
     {
         child.AcceptVisitor(this);
     }
 }
예제 #3
0
 public ElementWrapper(AXmlElement element)
 {
     this.LocalName  = element.LocalName;
     this.Prefix     = element.Prefix;
     this.Namespace  = element.Namespace;
     this.Offset     = element.StartOffset;
     this.Attributes = element.Attributes.Select(attr => new AttributeWrapper(attr)).ToList();
 }
예제 #4
0
        IList <ICompletionItem> CreateAttributeList(XamlCompletionContext context, bool includeEvents)
        {
            if (context.ParseInformation == null)
            {
                return(EmptyList <ICompletionItem> .Instance);
            }
            AXmlElement     lastElement = context.ActiveElement;
            IUnresolvedFile file        = context.ParseInformation.UnresolvedFile;
            XamlResolver    resolver    = new XamlResolver(compilation);
            IType           type        = resolver.ResolveType(lastElement.Namespace, lastElement.LocalName.Trim('.'));

            var list = new List <ICompletionItem>();

            string xamlPrefix = context.XamlNamespacePrefix;
            string xKey       = string.IsNullOrEmpty(xamlPrefix) ? "" : xamlPrefix + ":";

            if (lastElement.Prefix == context.XamlNamespacePrefix && XamlConst.IsBuiltin(lastElement.LocalName))
            {
                return(EmptyList <ICompletionItem> .Instance);
            }

            if (lastElement.LocalName.EndsWith(".", StringComparison.OrdinalIgnoreCase) || context.PressedKey == '.')
            {
                if (type.Kind == TypeKind.Unknown)
                {
                    return(EmptyList <ICompletionItem> .Instance);
                }

                if (context.ParentElement != null &&
                    context.ParentElement.LocalName.StartsWith(lastElement.LocalName.TrimEnd('.'), StringComparison.OrdinalIgnoreCase))
                {
                    AddAttributes(type, list, includeEvents);
                }
                AddAttachedProperties(type.GetDefinition(), list);
            }
            else
            {
                if (type.Kind == TypeKind.Unknown)
                {
                    list.Add(new XamlCompletionItem(xKey + "Uid"));
                }
                else
                {
                    AddAttributes(type, list, includeEvents);
                    list.AddRange(GetListOfAttached(context, null, includeEvents, true));
                    list.AddRange(
                        XamlConst.XamlNamespaceAttributes
                        .Where(localName => XamlConst.IsAttributeAllowed(context.InRoot, localName))
                        .Select(item => new XamlCompletionItem(xKey + item))
                        );
                }
            }

            return(list);
        }
예제 #5
0
        public static String GetPath(AXmlElement activeElement)
        {
            String      path   = activeElement.Name;
            AXmlElement parent = activeElement;

            while ((parent = AXmlFinder.FindOwnerElement(parent, false)) != null)
            {
                path = parent.Name + "\\" + path;
            }
            return(path);
        }
예제 #6
0
        public int GetIndex(AXmlObject objToSearch, bool CountCommentAsElement)
        {
            int  index    = 0;
            bool isInList = false;

            if (objToSearch != null && objToSearch.Parent != null && objToSearch.Parent is AXmlElement)
            {
                AXmlElement parent = objToSearch.Parent as AXmlElement;
                AXmlObject  temp   = objToSearch.Parent;
                while (parent == null && temp != null)
                {
                    parent = parent.Parent as AXmlElement;
                    temp   = temp.Parent;
                }

                if (parent != null)
                {
                    foreach (AXmlObject obj in parent.Children)
                    {
                        if (obj.Equals(objToSearch))
                        {
                            isInList = true;
                            break;//순서를 찾았다.
                        }
                        else if (objToSearch is AXmlElement && obj is AXmlElement)
                        {
                            index++;
                        }
                        else if (objToSearch is AXmlTag && (objToSearch as AXmlTag).OpeningBracket.Equals("<!--") && obj is AXmlElement)
                        {
                            if (CountCommentAsElement)
                            {
                                index++;
                            }
                        }
                        else if (obj is AXmlTag && (obj as AXmlTag).OpeningBracket.Equals("<!--"))
                        {
                            if (CountCommentAsElement)
                            {
                                index++;
                            }
                        }
                    }
                }
            }
            if (isInList)
            {
                return(index);
            }
            else
            {
                return(-1);
            }
        }
예제 #7
0
        public ElementContext(SourceFile file, AXmlElement element, ElementContext parent)
        {
            _file     = file;
            _element  = element;
            _parent   = parent;
            _children = _element.Children
                        .OfType <AXmlElement>()
                        .Select(elm => new ElementContext(_file, elm, this)).ToArray();

            _attributes = _element.Attributes.Select(a => new Attribute(_file, a)).ToArray();
        }
예제 #8
0
        public static AXmlAttribute GetAttribute(AXmlElement element, String attrName)
        {
            foreach (AXmlAttribute attr in element.Attributes)
            {
                if (attr.Name.Equals(attrName))
                {
                    return(attr);

                    break;
                }
            }
            return(null);
        }
        XamlOutlineNode BuildNode(AXmlElement item)
        {
            XamlOutlineNode node = new XamlOutlineNode {
                Name        = item.GetAttributeValue("Name") ?? item.GetAttributeValue(XamlConst.XamlNamespace, "Name"),
                ElementName = item.Name,
                Marker      = editor.Document.CreateAnchor(Utils.MinMax(item.StartOffset, 0, editor.Document.TextLength - 1)),
                EndMarker   = editor.Document.CreateAnchor(Utils.MinMax(item.EndOffset, 0, editor.Document.TextLength - 1)),
                Editor      = editor
            };

            foreach (var child in item.Children.OfType <AXmlElement>())
            {
                node.Children.Add(BuildNode(child));
            }

            return(node);
        }
        IClass AddClass(string className, AXmlElement element)
        {
            if (projectContent.Language == LanguageProperties.VBNet && projectContent.Project is IProject)
            {
                className = ((IProject)projectContent.Project).RootNamespace + "." + className;
            }

            DefaultClass c             = new DefaultClass(CompilationUnit, className);
            string       modifierValue = (element.GetAttributeValue(CompletionDataHelper.XamlNamespace, "ClassModifier") ?? string.Empty).Trim();

            c.Modifiers = ModifierEnum.Partial;

            string internalString = currentAmbience.ConvertAccessibility(ModifierEnum.Internal).Trim();

            if (projectContent.Language.NameComparer.Compare(modifierValue, internalString) == 0)
            {
                c.Modifiers |= ModifierEnum.Internal;
            }
            else
            {
                c.Modifiers |= ModifierEnum.Public;
            }

            c.Region = CreateRegion(element.StartOffset, element.EndOffset);
            var baseType = TypeFromXmlNode(CompilationUnit, element);

            if (baseType != null)
            {
                c.BaseTypes.Add(baseType);
            }
            CompilationUnit.Classes.Add(c);

            DefaultMethod initializeComponent = new DefaultMethod(
                "InitializeComponent",
                projectContent.SystemTypes.Void,
                ModifierEnum.Public | ModifierEnum.Synthetic, c.Region, DomRegion.Empty,
                c);

            c.Methods.Add(initializeComponent);

            return(c);
        }
예제 #11
0
            public override void VisitElement(AXmlElement element)
            {
                string name = element.GetAttributeValue(XamlConst.XamlNamespace, "Name") ??
                              element.GetAttributeValue("Name");
                string modifier = element.GetAttributeValue(XamlConst.XamlNamespace, "FieldModifier");

                if (name != null && TypeDefinition != null)
                {
                    var field = new DefaultUnresolvedField(TypeDefinition, name);
                    field.Accessibility = Accessibility.Internal;
                    field.ReturnType    = CreateTypeReference(element.Namespace, element.LocalName);
                    field.Region        = new DomRegion(file.FileName, textDocument.GetLocation(element.StartOffset), textDocument.GetLocation(element.EndOffset));
                    if (modifier != null)
                    {
                        field.Accessibility = ParseAccessibility(modifier);
                    }
                    TypeDefinition.Members.Add(field);
                }

                base.VisitElement(element);
            }
예제 #12
0
        public static List <AXmlObject> GetXmlElementPair(AXmlDocument xDoc, AXmlObject xmlObj)
        {
            List <AXmlObject> tsList = new List <AXmlObject>();
            AXmlElement       ele    = FindOwnerElement(xmlObj, true);

            if (ele == null)
            {
                return(new List <AXmlObject>());
            }

            if (ele.HasStartOrEmptyTag)
            {
                tsList.Add(ele.Children[0]);
            }
            if (ele.HasEndTag)
            {
                tsList.Add(ele.Children[ele.Children.Count - 1]);
            }

            return(tsList);
        }
        public override void VisitElement(AXmlElement element)
        {
            AXmlTag tag = element.Children.FirstOrDefault() as AXmlTag;

            if (tag != null && tag.IsStartOrEmptyTag)
            {
                NodeWrapper node = new NodeWrapper()
                {
                    ElementName = element.LocalName,
                    StartOffset = element.StartOffset,
                    EndOffset   = element.EndOffset,
                    Name        = element.GetAttributeValue("Name") ?? element.GetAttributeValue(CompletionDataHelper.XamlNamespace, "Name"),
                    Children    = new List <NodeWrapper>()
                };

                if (CompilationUnit.TreeRootNode == null)
                {
                    CompilationUnit.TreeRootNode = node;
                    nodeStack.Push(CompilationUnit.TreeRootNode);
                }
                else
                {
                    if (nodeStack.Count > 0)
                    {
                        nodeStack.Peek().Children.Add(node);
                    }
                    if (!tag.IsEmptyTag)
                    {
                        nodeStack.Push(node);
                    }
                }
            }

            base.VisitElement(element);

            if (tag != null && tag.IsStartTag)
            {
                nodeStack.PopOrDefault();
            }
        }
예제 #14
0
        /// <summary>
        /// 부모노드에서 몇번째에 속한 element인지를 찾는다.
        /// </summary>
        /// <param name="element">index를 찾을 element</param>
        /// <param name="CountCommentAsElement">Comment를 Element로 인식하고 count할 것인지 여부</param>
        /// <returns>element의 index가 부모노드에서 몇번인지. 0 based.</returns>
        public static int GetIndexFromParent(AXmlElement element, bool CountCommentAsElement = true)
        {
            AXmlElement parent = element.Parent as AXmlElement;
            AXmlObject  temp   = element.Parent;
            int         index  = 0;

            while (parent == null && temp != null)
            {
                parent = parent.Parent as AXmlElement;
                temp   = temp.Parent;
            }
            if (parent != null)
            {
                foreach (AXmlObject obj in parent.Children)
                {
                    if (obj.Equals(element))
                    {
                        return(index);

                        break;//순서를 찾았다.
                    }
                    else if (element is AXmlElement && obj is AXmlElement)
                    {
                        index++;
                    }
                    else if (obj is AXmlTag && (obj as AXmlTag).OpeningBracket.Equals("<!--"))
                    {
                        if (CountCommentAsElement)
                        {
                            index++;
                        }
                    }
                }
            }

            return(-1);
        }
예제 #15
0
        public IList <ICompletionItem> CreateElementList(XamlCompletionContext context, bool includeAbstract)
        {
            if (context.ParseInformation == null)
            {
                return(EmptyList <ICompletionItem> .Instance);
            }

            List <ICompletionItem> result = new List <ICompletionItem>();
            AXmlElement            last   = context.ParentElement;
            ITextEditor            editor = context.Editor;

            compilation = SD.ParserService.GetCompilationForFile(editor.FileName);
            IUnresolvedFile file = context.ParseInformation.UnresolvedFile;

            foreach (string item in XamlConst.GetAllowedItems(context))
            {
                result.Add(new XamlCompletionItem(item));
            }

            IType rt = null;

            if (last != null)
            {
                if (string.Equals(last.Prefix, context.XamlNamespacePrefix, StringComparison.OrdinalIgnoreCase))
                {
                    if (string.Equals(last.LocalName, "Members", StringComparison.OrdinalIgnoreCase))
                    {
                        return(result);
                    }
                    if (string.Equals(last.LocalName, "Code", StringComparison.OrdinalIgnoreCase))
                    {
                        return(result);
                    }
                }
                // If we have an element that is not a property or an incomplete
                // definition => interpret element as a type.
                XamlResolver resolver = new XamlResolver(compilation);
                int          dotIndex = last.LocalName.IndexOf(".", StringComparison.Ordinal) + 1;
                if (dotIndex < 1 || dotIndex == last.LocalName.Length)
                {
                    rt = resolver.ResolveType(last.Namespace, last.LocalName.Trim('.'));
                    string contentPropertyName = GetContentPropertyName(rt.GetDefinition());
                    // If the type has a content property specified, use its type for completion.
                    if (!string.IsNullOrEmpty(contentPropertyName))
                    {
                        IProperty p = rt.GetProperties(m => m.Name == contentPropertyName).FirstOrDefault();
                        if (p != null)
                        {
                            rt = p.ReturnType;
                        }
                    }
                }
                else
                {
                    string typeName   = last.LocalName.Substring(0, dotIndex - 1);
                    string memberName = last.LocalName.Substring(dotIndex);
                    rt = resolver.ResolveType(last.Namespace, typeName);
                    IMember member = rt.GetMembers(m => m.Name == memberName).FirstOrDefault();
                    if (member != null)
                    {
                        rt = member.ReturnType;
                    }
                }
            }

            bool            parentAdded    = false;
            var             utd            = file.GetInnermostTypeDefinition(editor.Caret.Location);
            ITypeDefinition currentTypeDef = null;

            if (utd != null)
            {
                currentTypeDef = utd.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly)).GetDefinition();
            }
            MemberLookup memberLookup = new MemberLookup(currentTypeDef, compilation.MainAssembly);

            IList <ITypeDefinition> possibleTypesInCollection = EmptyList <ITypeDefinition> .Instance;

            if (rt != null && Extensions.IsListType(rt))
            {
                possibleTypesInCollection = rt.GetMethods(m => m.Parameters.Count == 1 && "Add".Equals(m.Name, StringComparison.Ordinal))
                                            .Select(m => m.Parameters[0].Type.GetDefinition())
                                            .Where(t => t != null)
                                            .ToList();
            }

            var items = GetClassesFromContext(context);

            foreach (var ns in items)
            {
                foreach (ITypeDefinition td in ns.Value)
                {
                    if (td.Kind != TypeKind.Class && (!includeAbstract || td.Kind != TypeKind.Interface))
                    {
                        continue;
                    }
                    if (td.IsStatic || (!includeAbstract && td.IsAbstract) || td.IsDerivedFrom(KnownTypeCode.Attribute))
                    {
                        continue;
                    }
                    if (td.Kind == TypeKind.Class && !td.GetConstructors().Any(m => memberLookup.IsAccessible(m, false)))
                    {
                        continue;
                    }
                    if (possibleTypesInCollection.Count > 0 && !possibleTypesInCollection.Any(td.IsDerivedFrom))
                    {
                        continue;
                    }
                    string fullName = td.Name;
                    if (!string.IsNullOrEmpty(ns.Key))
                    {
                        fullName = ns.Key + ":" + fullName;
                    }
                    XamlCompletionItem item = new XamlCompletionItem(fullName, td);
                    parentAdded = parentAdded || (last != null && item.Text == last.Name);
                    result.Add(item);
                }
            }

            // TODO reimplement this if it is really necessary.
//			if (!parentAdded && last != null && !last.Name.Contains(".")) {
//				IClass itemClass = cu.CreateType(last.Namespace, last.LocalName.Trim('.')).GetUnderlyingClass();
//				if (itemClass != null)
//					result.Add(new XamlCodeCompletionItem(itemClass, last.Prefix));
//			}

            return(result);
        }
예제 #16
0
            public override void VisitDocument(AXmlDocument document)
            {
                currentDocument = document;
                AXmlElement rootElement = currentDocument.Children.OfType <AXmlElement>().FirstOrDefault();

                if (rootElement != null)
                {
                    string className = rootElement.GetAttributeValue(XamlConst.XamlNamespace, "Class");
                    string modifier  = rootElement.GetAttributeValue(XamlConst.XamlNamespace, "ClassModifier");
                    if (className != null)
                    {
                        TypeDefinition = new DefaultUnresolvedTypeDefinition(className)
                        {
                            Kind           = TypeKind.Class,
                            UnresolvedFile = file,
                            Accessibility  = Accessibility.Public,
                            Region         = new DomRegion(file.FileName, textDocument.GetLocation(rootElement.StartOffset), textDocument.GetLocation(rootElement.EndOffset))
                        };
                        TypeDefinition.Members.Add(
                            new DefaultUnresolvedMethod(TypeDefinition, "InitializeComponent")
                        {
                            Accessibility = Accessibility.Public,
                            ReturnType    = KnownTypeReference.Void
                        });
                        TypeDefinition.Members.Add(
                            new DefaultUnresolvedField(TypeDefinition, "_contentLoaded")
                        {
                            Accessibility = Accessibility.Private,
                            ReturnType    = KnownTypeReference.Boolean
                        });

                        var connectMember =
                            new DefaultUnresolvedMethod(TypeDefinition, "Connect")
                        {
                            Accessibility = Accessibility.Private,
                            ReturnType    = KnownTypeReference.Void
                        };
                        connectMember.Parameters.Add(new DefaultUnresolvedParameter(KnownTypeReference.Int32, "connectionId"));
                        connectMember.Parameters.Add(new DefaultUnresolvedParameter(KnownTypeReference.Object, "target"));
                        TypeDefinition.Members.Add(connectMember);
                        connectMember.ExplicitInterfaceImplementations.Add(
                            new DefaultMemberReference(SymbolKind.Method, new GetClassTypeReference(new FullTypeName(typeof(System.Windows.Markup.IComponentConnector).FullName)), "Connect"));

                        var browsableAttribute = new DefaultUnresolvedAttribute(new GetClassTypeReference(new FullTypeName(typeof(System.ComponentModel.EditorBrowsableAttribute).FullName)));

                        browsableAttribute.PositionalArguments.Add(
                            new SimpleConstantValue(
                                new GetClassTypeReference(new FullTypeName(typeof(System.ComponentModel.EditorBrowsableAttribute).FullName)), System.ComponentModel.EditorBrowsableState.Never
                                ));

                        connectMember.Attributes.Add(browsableAttribute);
                        TypeDefinition.BaseTypes.Add(CreateTypeReference(rootElement.Namespace, rootElement.LocalName));
                        TypeDefinition.BaseTypes.Add(new GetClassTypeReference(new FullTypeName(typeof(System.Windows.Markup.IComponentConnector).FullName)));
                        if (modifier != null)
                        {
                            TypeDefinition.Accessibility = ParseAccessibility(modifier);
                        }
                    }
                }
                base.VisitDocument(document);
            }
 static IReturnType TypeFromXmlNode(XamlCompilationUnit cu, AXmlElement element)
 {
     return(cu.CreateType(element.Namespace, element.LocalName));
 }
예제 #18
0
        /// <summary>
        /// get the first xmlobject from baseNode by xpath. <br/>
        /// if there are multiple objects in baseNode, <br/>
        /// fill list argument. this function will fill this list with all xml objects<br/>
        /// that have the path.<br/>
        /// </summary>
        /// <param name="baseNode">if you don't know root, call GetRoot(AXmlDocument xDoc) static method.</param>
        /// <param name="xPath">seperator is '/'. ex>Command/Data</param>
        /// <param name="list">if null, this function just return the first Node and end. but if not null, all reference will be inserted in this list</param>
        /// <returns>the first XmlNode which has the path of xPath, formatted of AXmlObject</returns>
        public static AXmlObject GetXmlObject(AXmlElement baseNode, String xPath, List <AXmlObject> list = null)
        {
            String     firstNodeName = xPath; // '/'가 없는 문자열일 경우 그 자체가 이름..
            String     lastPath      = "";
            AXmlObject selectedObj   = null;
            AXmlObject firstSelected = null;

            if (baseNode == null)
            {
                return(null);
            }

            if (xPath.Contains('/'))
            {
                firstNodeName = xPath.Substring(0, xPath.IndexOf("/"));
                lastPath      = xPath.Substring(xPath.IndexOf('/') + 1);

                if (firstNodeName.Equals(baseNode.Name))
                {
                    if (lastPath.Contains('/'))
                    {
                        firstNodeName = lastPath.Substring(0, lastPath.IndexOf("/"));
                        lastPath      = lastPath.Substring(lastPath.IndexOf('/') + 1);
                    }
                    else
                    {
                        firstNodeName = lastPath;
                        lastPath      = "";
                    }
                }
            }

            if (lastPath.Length == 0 && baseNode.Name.ToLower().Equals(firstNodeName.ToLower()))
            {
                list.Add(baseNode);
                return(baseNode);
            }
            else
            {
                foreach (AXmlObject obj in baseNode.Children)
                {
                    if (obj is AXmlElement)
                    {
                        AXmlElement element = (obj as AXmlElement);
                        if (element.Name.Equals(firstNodeName))
                        {//첫 노드를 찾았으니 다음으로 넘어가야 한다.
                            if (lastPath.Length == 0)
                            {
                                selectedObj = element;
                            }
                            else
                            {
                                selectedObj = GetXmlObject(element, lastPath, list);
                            }

                            if (selectedObj != null)
                            {
                                if (list == null)
                                {
                                    return(selectedObj);
                                }
                                else
                                {
                                    if (firstSelected == null)
                                    {
                                        firstSelected = selectedObj;
                                    }
                                    list.Add(selectedObj);
                                }
                            }
                        }
                    }
                    else if (obj is AXmlAttribute && firstNodeName[0].Equals('@'))//Attribute일 경우, XPath의 첫글자는 @로 시작해야 한다.
                    {
                        AXmlAttribute attr = (obj as AXmlAttribute);
                        if (attr.Name.Equals(firstNodeName))
                        {//첫 노드를 찾았으니 다음으로 넘어가야 한다.
                            selectedObj = attr;
                            if (selectedObj != null)
                            {
                                if (list == null)
                                {
                                    return(selectedObj);
                                }
                                else
                                {
                                    if (firstSelected == null)
                                    {
                                        firstSelected = selectedObj;
                                    }
                                    list.Add(selectedObj);
                                }
                            }
                        }
                    }
                }
            }
            return(firstSelected);
        }
예제 #19
0
        public void ActiveOnOffset(int textOffset)
        {
            SetCaretOffset(textOffset);
            AXmlObject xmlObj = xDoc.GetChildAtOffset(textOffset);

            backgroundRenderer.HighlightColor = Color.FromArgb(0x40, 0, 0, 0xFF);
            ActiveObject = xmlObj;

            _activeIndex = -1; //초기값..

            if (xmlObj is AXmlText)
            {
                if (xmlObj.Parent != null && xmlObj.Parent is AXmlTag)
                {
                    AXmlTag tag = xmlObj.Parent as AXmlTag;
                    if (tag.OpeningBracket.Equals("<!--"))//comment
                    {
                        ActiveComment = tag;
                        ActiveElement = null;
                        _activeIndex  = GetIndex(tag, true);
                    }
                    else
                    {
                        ActiveComment = null;
                    }
                }
                else
                {
                    ActiveComment = null;
                }
            }
            else if (xmlObj is AXmlTag)
            {
                AXmlTag tag = xmlObj as AXmlTag;
                if (tag.OpeningBracket.Equals("<!--"))//comment
                {
                    ActiveComment = tag;
                    ActiveElement = null;
                    _activeIndex  = GetIndex(tag, true);
                }
                else
                {
                    ActiveComment = null;
                }
            }
            else
            {
                ActiveComment = null;
            }

            if (ActiveComment == null)
            {
                ActiveElement = AXmlFinder.FindOwnerElement(xmlObj, true);
                if (ActiveElement != null)
                {
                    _activeIndex = GetIndex(ActiveElement, true);
                }
            }

            if (xmlObj is AXmlAttribute)
            {
                ActiveAttribute = xmlObj as AXmlAttribute;
            }
            else if ((xmlObj is AXmlElement) == false && (xmlObj is AXmlTag))
            {
                ActiveAttribute = null;
            }
            else
            {
                ActiveAttribute = null;
            }



            if (ActiveComment != null)
            {
                backgroundRenderer.HighlightObjects = new AXmlObject[] { ActiveComment }
            }
예제 #20
0
        /// <summary>
        /// find the element which has xmlObj as a child or grand x child.
        /// </summary>
        /// <param name="xmlObj">start point</param>
        /// <param name="useItSelfIfElement">if start point is element, return this one</param>
        /// <param name="elementName">find parent </param>
        /// <returns>parent element which has xmlObj as a child or grand x child</returns>
        public static AXmlElement FindOwnerElement(AXmlObject xmlObj, bool useItSelfIfElement = false, String elementName = null, bool ignoreCases = true)
        {
            if (useItSelfIfElement)
            {
                if (xmlObj is AXmlElement)
                {
                    if (elementName == null)
                    {
                        return(xmlObj as AXmlElement);
                    }
                    else if (ignoreCases)
                    {
                        if ((xmlObj as AXmlElement).Name.ToLower().Equals(elementName.ToLower()))
                        {
                            return(xmlObj as AXmlElement);
                        }
                    }
                    else
                    {
                        if ((xmlObj as AXmlElement).Name.Equals(elementName))
                        {
                            return(xmlObj as AXmlElement);
                        }
                    }
                }
            }
            AXmlObject temp = xmlObj.Parent;

            if (temp == null)
            {
                return(null);              //the end of node
            }
            if (elementName == null)
            {
                while (temp != null && (temp is AXmlElement) == false)
                {
                    temp = temp.Parent;
                }
            }
            else //there is parent name which will be found.
            {
                AXmlElement parent = null;
                while (temp != null)
                {
                    if (temp is AXmlElement)
                    {
                        if (ignoreCases)
                        {
                            if ((temp as AXmlElement).Name.ToLower().Equals(elementName.ToLower()))
                            {
                                parent = temp as AXmlElement;
                                break;
                            }
                        }
                        else
                        {
                            if ((temp as AXmlElement).Name.Equals(elementName))
                            {
                                parent = temp as AXmlElement;
                                break;
                            }
                        }
                    }
                    temp = temp.Parent;
                }
                return(parent);
            }
            if ((temp is AXmlElement) == false)
            {
                return(null);
            }
            else
            {
                return(temp as AXmlElement);
            }
        }
        public static XamlContext ResolveContext(FileName fileName, ITextSource fileContent, int offset)
        {
            XamlFullParseInformation info = SD.ParserService.Parse(fileName, fileContent) as XamlFullParseInformation;

            if (info == null)
            {
                throw new Exception("need full parse info!");
            }

            AXmlDocument document    = info.Document;
            AXmlObject   currentData = document.GetChildAtOffset(offset);

            string         attributeName = string.Empty, attributeValue = string.Empty;
            AttributeValue value                = null;
            bool           isRoot               = false;
            bool           wasAXmlElement       = false;
            int            offsetFromValueStart = -1;

            List <AXmlElement> ancestors             = new List <AXmlElement>();
            Dictionary <string, XamlNamespace> xmlns = new Dictionary <string, XamlNamespace>();
            List <string> ignored             = new List <string>();
            string        xamlNamespacePrefix = string.Empty;

            var         item = currentData;
            AXmlElement root = null;

            while (item != document)
            {
                if (item is AXmlElement)
                {
                    AXmlElement element = item as AXmlElement;
                    ancestors.Add(element);
                    foreach (var attr in element.Attributes)
                    {
                        if (attr.IsNamespaceDeclaration)
                        {
                            string prefix = (attr.Name == "xmlns") ? "" : attr.LocalName;
                            if (!xmlns.ContainsKey(prefix))
                            {
                                xmlns.Add(prefix, new XamlNamespace(attr.Value));
                            }
                        }

                        if (attr.LocalName == "Ignorable" && attr.Namespace == XamlConst.MarkupCompatibilityNamespace)
                        {
                            ignored.AddRange(attr.Value.Split(' ', '\t'));
                        }

                        if (string.IsNullOrEmpty(xamlNamespacePrefix) && attr.Value == XamlConst.XamlNamespace)
                        {
                            xamlNamespacePrefix = attr.LocalName;
                        }
                    }

                    if (element.Parent is AXmlDocument)
                    {
                        root = element;
                        if (!wasAXmlElement)
                        {
                            isRoot = true;
                        }
                    }

                    wasAXmlElement = true;
                }

                item = item.Parent;
            }

            XamlContextDescription description = XamlContextDescription.None;

            AXmlElement active = null;
            AXmlElement parent = null;

            if (currentData is AXmlAttribute)
            {
                AXmlAttribute a = currentData as AXmlAttribute;
                int           valueStartOffset = a.ValueSegment.Offset + 1;
                attributeName  = a.Name;
                attributeValue = a.Value;
                value          = MarkupExtensionParser.ParseValue(attributeValue);

                if (offset >= valueStartOffset && (offset < a.EndOffset ||              // if length is < 2 one quote is missing
                                                   (a.ValueSegment.Length <= 1 && offset <= a.EndOffset)))
                {
                    offsetFromValueStart = offset - valueStartOffset;

                    description = XamlContextDescription.InAttributeValue;

                    if (value != null && !value.IsString)
                    {
                        description = XamlContextDescription.InMarkupExtension;
                    }
                    if (attributeValue.StartsWith("{}", StringComparison.Ordinal) && attributeValue.Length > 2)
                    {
                        description = XamlContextDescription.InAttributeValue;
                    }
                }
                else
                {
                    description = XamlContextDescription.InTag;
                }
                active = a.ParentElement;
            }
            else if (currentData is AXmlTag)
            {
                AXmlTag tag = currentData as AXmlTag;
                if (tag.IsStartOrEmptyTag || tag.IsEndTag)
                {
                    if (tag.NameSegment.EndOffset < offset)
                    {
                        description = XamlContextDescription.InTag;
                    }
                    else
                    {
                        description = XamlContextDescription.AtTag;
                    }
                }
                else if (tag.IsComment)
                {
                    description = XamlContextDescription.InComment;
                }
                else if (tag.IsCData)
                {
                    description = XamlContextDescription.InCData;
                }
                active = tag.Parent as AXmlElement;
            }

            if (active != ancestors.FirstOrDefault())
            {
                parent = ancestors.FirstOrDefault();
            }
            else
            {
                parent = ancestors.Skip(1).FirstOrDefault();
            }

            if (active == null)
            {
                active = parent;
            }

            var xAttribute = currentData as AXmlAttribute;

            var context = new XamlContext()
            {
                Description         = description,
                ActiveElement       = active,
                ParentElement       = parent,
                RootElement         = root,
                Ancestors           = ancestors.AsReadOnly(),
                Attribute           = xAttribute,
                InRoot              = isRoot,
                AttributeValue      = value,
                RawAttributeValue   = attributeValue,
                ValueStartOffset    = offsetFromValueStart,
                XmlnsDefinitions    = xmlns,
                ParseInformation    = info,
                IgnoredXmlns        = ignored.AsReadOnly(),
                XamlNamespacePrefix = xamlNamespacePrefix
            };

            return(context);
        }
예제 #22
0
 public static ElementWrapper ToWrapper(this AXmlElement element)
 {
     return(new ElementWrapper(element));
 }
예제 #23
0
 public static QualifiedNameWithLocation ToQualifiedName(this AXmlElement thisValue)
 {
     return(new QualifiedNameWithLocation(thisValue.LocalName, thisValue.Namespace, thisValue.Prefix, thisValue.StartOffset));
 }