summaryrefslogtreecommitdiff
path: root/xml
diff options
context:
space:
mode:
authorJean-Baptiste Queru <jbq@google.com>2013-04-01 14:41:51 -0700
committerJean-Baptiste Queru <jbq@google.com>2013-04-01 14:41:51 -0700
commit2bd2b7c2623d4266384e890271869efc044aabff (patch)
tree0b31f50e55975b6354ed458314e17b4441bb4e17 /xml
parent1d526b16d476792ca7ce47616d55833115e8d6ab (diff)
downloadidea-2bd2b7c2623d4266384e890271869efc044aabff.tar.gz
Snapshot ee98b298267d0e09d2cd2f0731b6480a56dd48e7 from master branch of git://git.jetbrains.org/idea/community.git
Change-Id: I4515f72af131fdea9fc6905a4dc0fe9532409a81
Diffstat (limited to 'xml')
-rw-r--r--xml/dom-impl/dom-impl.iml1
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/DTDModelLoader.java339
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/DomGenDialog.java79
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/DomGenPanel.form137
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/DomGenPanel.java177
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/Emitter.java36
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/FieldDesc.java78
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/FileManager.java33
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/GenerateDomModelAction.java34
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/JetBrainsEmitter.java679
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/Main.java61
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/MergingFileManager.java248
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/ModelDesc.java171
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/ModelGen.java189
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/ModelLoader.java28
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/NamespaceDesc.java84
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/TypeDesc.java55
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/Util.java224
-rw-r--r--xml/dom-impl/src/com/intellij/util/dom/generator/XSDModelLoader.java681
-rw-r--r--xml/dom-impl/src/com/intellij/util/xml/EnumConverter.java2
-rw-r--r--xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java3
-rw-r--r--xml/dom-impl/src/com/intellij/util/xml/impl/FileDescriptionCachedValueProvider.java7
-rw-r--r--xml/dom-openapi/src/com/intellij/util/xml/ui/ErrorableTableCellRenderer.java2
-rw-r--r--xml/impl/resources/inspectionDescriptions/XmlInvalidId.html6
-rw-r--r--xml/impl/resources/liveTemplates/zen_html.xml17
-rw-r--r--xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.form18
-rw-r--r--xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.java6
-rw-r--r--xml/impl/src/com/intellij/application/options/emmet/EmmetOptions.java9
-rw-r--r--xml/impl/src/com/intellij/codeInsight/actions/GenerateDTDAction.java42
-rw-r--r--xml/impl/src/com/intellij/codeInsight/completion/XmlSmartEnterProcessor.java13
-rw-r--r--xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java7
-rw-r--r--xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/AddSchemaPrefixIntention.java6
-rw-r--r--xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ConvertSchemaPrefixToDefaultIntention.java3
-rw-r--r--xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java8
-rw-r--r--xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FetchExtResourceAction.java35
-rw-r--r--xml/impl/src/com/intellij/codeInsight/editorActions/moveUpDown/XmlMover.java2
-rw-r--r--xml/impl/src/com/intellij/codeInsight/intentions/XmlChooseColorIntentionAction.java10
-rw-r--r--xml/impl/src/com/intellij/codeInsight/template/emmet/XmlEmmetParser.java4
-rw-r--r--xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java4
-rw-r--r--xml/impl/src/com/intellij/codeInsight/template/emmet/generators/XmlZenCodingGeneratorImpl.java2
-rw-r--r--xml/impl/src/com/intellij/codeInsight/template/emmet/nodes/GenerationNode.java26
-rw-r--r--xml/impl/src/com/intellij/codeInspection/htmlInspections/AddCustomTagOrAttributeIntentionAction.java15
-rw-r--r--xml/impl/src/com/intellij/codeInspection/htmlInspections/AddHtmlTagOrAttributeToCustomsIntention.java17
-rw-r--r--xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownAttributeInspection.java4
-rw-r--r--xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownTagInspection.java5
-rw-r--r--xml/impl/src/com/intellij/codeInspection/htmlInspections/RequiredAttributesInspection.java7
-rw-r--r--xml/impl/src/com/intellij/javaee/ExternalResourceManagerImpl.java4
-rw-r--r--xml/impl/src/com/intellij/javaee/HtmlLanguageLevelForm.java4
-rw-r--r--xml/impl/src/com/intellij/lang/html/structureView/Html5SectionsNodeProvider.java3
-rw-r--r--xml/impl/src/com/intellij/psi/formatter/xml/AbstractXmlBlock.java29
-rw-r--r--xml/impl/src/com/intellij/psi/formatter/xml/XmlBlock.java46
-rw-r--r--xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/URIReferenceProvider.java13
-rw-r--r--xml/impl/src/com/intellij/psi/impl/source/xml/TagNameReference.java8
-rw-r--r--xml/impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java2
-rw-r--r--xml/impl/src/com/intellij/xml/DefaultXmlExtension.java115
-rw-r--r--xml/impl/src/com/intellij/xml/arrangement/XmlArrangementVisitor.java13
-rw-r--r--xml/impl/src/com/intellij/xml/arrangement/XmlElementArrangementEntry.java18
-rw-r--r--xml/impl/src/com/intellij/xml/arrangement/XmlRearranger.java125
-rw-r--r--xml/impl/src/com/intellij/xml/impl/schema/XmlElementDescriptorImpl.java6
-rw-r--r--xml/impl/src/com/intellij/xml/util/HtmlUtil.java5
-rw-r--r--xml/impl/src/com/intellij/xml/util/XmlDuplicatedIdInspection.java77
-rw-r--r--xml/impl/src/com/intellij/xml/util/XmlInvalidIdInspection.java68
-rw-r--r--xml/impl/src/com/intellij/xml/util/XmlReferenceContributor.java6
-rw-r--r--xml/impl/src/com/intellij/xml/util/XmlUtil.java7
-rw-r--r--xml/openapi/src/com/intellij/patterns/XmlAttributeValuePattern.java4
-rw-r--r--xml/openapi/src/com/intellij/patterns/XmlNamedElementPattern.java10
-rw-r--r--xml/openapi/src/com/intellij/psi/xml/XmlAttribute.java7
-rw-r--r--xml/openapi/src/com/intellij/psi/xml/XmlTagChild.java1
-rw-r--r--xml/openapi/src/com/intellij/xml/breadcrumbs/BreadcrumbsComponent.java8
-rw-r--r--xml/relaxng/src/org/intellij/plugins/relaxNG/RelaxNGReferenceContributor.java11
-rw-r--r--xml/tests/src/com/intellij/codeInsight/completion/XmlCompletionTest.java40
-rw-r--r--xml/tests/src/com/intellij/codeInsight/completion/XmlSmartEnterTest.java5
-rw-r--r--xml/tests/src/com/intellij/codeInsight/daemon/XmlHighlightingTest.java1
-rw-r--r--xml/tests/src/com/intellij/codeInsight/daemon/quickFix/ExtractExternalResourceLinksTest.java59
-rw-r--r--xml/tests/src/com/intellij/codeInsight/template/XmlLiveTemplateTest.groovy6
-rw-r--r--xml/tests/src/com/intellij/codeInspection/htmlInspections/XmlInspectionToolProvider.java (renamed from xml/impl/src/com/intellij/codeInspection/htmlInspections/XmlInspectionToolProvider.java)0
-rw-r--r--xml/tests/src/com/intellij/xml/arrangement/XmlRearrangerTest.groovy9
-rw-r--r--xml/tests/testData/mover/tag5_afterDown.xml11
-rw-r--r--xml/tests/testData/quickFix/fetchExternalResources/BPMN20.xsd37
-rw-r--r--xml/tests/testData/smartEnter/IDEADEV_29628_after.xml2
-rw-r--r--xml/tests/testData/smartEnter/idea103417_1.xml1
-rw-r--r--xml/tests/testData/smartEnter/idea103417_1_after.xml1
-rw-r--r--xml/tests/testData/smartEnter/idea103417_2.xml1
-rw-r--r--xml/tests/testData/smartEnter/idea103417_2_after.xml1
-rw-r--r--xml/tests/testData/xml/DuplicateIdAttribute.xml4
-rw-r--r--xml/tests/testData/xml/SchemaReferencesValidation.xsd8
86 files changed, 573 insertions, 3817 deletions
diff --git a/xml/dom-impl/dom-impl.iml b/xml/dom-impl/dom-impl.iml
index 8b2feb012eaf..20cf593a6ece 100644
--- a/xml/dom-impl/dom-impl.iml
+++ b/xml/dom-impl/dom-impl.iml
@@ -18,7 +18,6 @@
<orderEntry type="module" module-name="lang-api" />
<orderEntry type="module" module-name="lang-impl" />
<orderEntry type="module" module-name="xml-openapi" />
- <orderEntry type="library" name="DTDParser" level="project" />
<orderEntry type="module" module-name="platform-resources" />
</component>
<component name="copyright">
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/DTDModelLoader.java b/xml/dom-impl/src/com/intellij/util/dom/generator/DTDModelLoader.java
deleted file mode 100644
index d4f23cd49770..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/DTDModelLoader.java
+++ /dev/null
@@ -1,339 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import com.wutka.dtd.*;
-import org.apache.xerces.xni.parser.XMLEntityResolver;
-
-import java.io.File;
-import java.util.*;
-
-/**
- * @author Gregory.Shrago
- * @author Konstantin Bulenkov
- */
-public class DTDModelLoader implements ModelLoader {
- private ModelDesc model;
-
- public void loadModel(ModelDesc model, Collection<File> schemas, XMLEntityResolver resolver) throws Exception {
- this.model = model;
- for (File dtdFile : schemas) {
- String fileName = dtdFile.getPath();
- if (dtdFile.isDirectory() || !fileName.endsWith(".dtd") || fileName.endsWith("datatypes.dtd")) {
- Util.log("skipping " + fileName);
- continue;
- }
- Util.log("loading " + fileName+"..");
- String ns = fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1);
- //loadDTDByXerces(ns, dtdFile, resolver);
-
- loadDTDByWutka(ns, dtdFile);
-
- }
- }
-
- private NamespaceDesc ensureNamespaceExists(String ns) {
- if (!model.nsdMap.containsKey(ns)) {
- Util.log("Adding default ns desc for: " + ns);
- NamespaceDesc nsd = new NamespaceDesc(ns, model.nsdMap.get(""));
- model.nsdMap.put(ns, nsd);
- }
- return model.nsdMap.get(ns);
- }
-
-
- private void loadDTDByWutka(String ns, File dtdFile) throws Exception {
- DTDParser parser = new DTDParser(dtdFile, false);
- // Parse the DTD and ask the parser to guess the root element
- DTD dtd = parser.parse(true);
- checkDTDRootElement(dtd);
- processDTD(ns, dtd, model.jtMap, model.nsdMap);
- }
-
-
- private void processDTD(String namespace, DTD dtd, Map<String, TypeDesc> jtMap, Map<String, NamespaceDesc> nsdMap) {
- final NamespaceDesc nsd = ensureNamespaceExists(namespace);
- if (nsd.skip) return;
- final ArrayList<String> resultQNames = new ArrayList<String>();
- final DTDElement[] elements = new DTDElement[dtd.elements.size()];
- int ptr = 1;
-
- final HashSet<DTDElement> visitedElements = new HashSet<DTDElement>();
- elements[0] = dtd.rootElement;
-
- while (--ptr > -1) {
- final DTDElement el = elements[ptr];
- visitedElements.add(el);
- final String typeName = model.toJavaTypeName(el.name, namespace);
- final String typeQName = model.toJavaQualifiedTypeName(namespace, typeName, false);
- if (resultQNames.contains(typeQName)) {
- continue;
- } else {
- resultQNames.add(typeQName);
- }
- final TypeDesc td = new TypeDesc(el.name, namespace, typeName, TypeDesc.TypeEnum.CLASS);
- boolean duplicates = false;
- if ((el.content instanceof DTDAny) || (el.content instanceof DTDMixed)) {
- FieldDesc fd = new FieldDesc(FieldDesc.SIMPLE, "value", "String", null, "null", false);
- fd.realIndex = td.fdMap.size();
- td.fdMap.put(fd.name, fd);
- }
- for (Object o : el.attributes.keySet()) {
- String attrName = (String) o;
- DTDAttribute attr = (DTDAttribute) el.attributes.get(attrName);
- if (attr.decl == DTDDecl.FIXED || "ID".equals(attr.type)) {
- continue;
- }
- boolean required = attr.decl == DTDDecl.REQUIRED;
- FieldDesc fd1 = new FieldDesc(FieldDesc.ATTR, Util.toJavaFieldName(attrName), "String", null, "\"\"", required);
- fd1.tagName = attrName;
- fd1.documentation = "Attribute " + attrName + "";
- fd1.realIndex = td.fdMap.size();
- duplicates = Util.addToNameMap(td.fdMap, fd1, false) || duplicates;
- }
- final ArrayList<List<DTDItem>> choiceList = new ArrayList<List<DTDItem>>();
- final LinkedList<Entry> plist = new LinkedList<Entry>();
- if (el.content instanceof DTDContainer) {
- //if ((el.content instanceof DTDChoice) || (el.content instanceof DTDSequence)) {
- plist.add(new Entry(el.content, false, true));
- }
- while (!plist.isEmpty()) {
- final Entry pentry = plist.removeFirst();
-
- final DTDItem p = pentry.p;
-
- if (p instanceof DTDName) {
- final DTDName n = (DTDName) p;
- final DTDElement nel = (DTDElement) dtd.elements.get(n.value);
- final String pName = n.value;
- final FieldDesc fd1 = new FieldDesc(FieldDesc.STR, Util.toJavaFieldName(pName), pName, null, "null", pentry.required && (n.cardinal == DTDCardinal.ONEMANY || n.cardinal == DTDCardinal.NONE));
- fd1.tagName = pName;
- if (nel != null) {
- fd1.documentation = parseDTDItemDocumentation(dtd, nel, "Type " + nel.name + " documentation");
- }
- if (nel == null) {
- fd1.type = model.toJavaTypeName(fd1.tagName, namespace);
- } else if (nel.content instanceof DTDEmpty || nel.content instanceof DTDAny) {
- boolean hasAttrFields = false;
- boolean hasTextContents = nel.content instanceof DTDAny;
- for (Object o : nel.attributes.values()) {
- DTDAttribute attr = (DTDAttribute) o;
- if (attr.decl != DTDDecl.FIXED && !"ID".equals(attr.type)) {
- hasAttrFields = true;
- break;
- }
- }
- if (hasAttrFields || hasTextContents) {
- fd1.clType = FieldDesc.OBJ;
- fd1.type = model.toJavaTypeName(fd1.tagName, namespace);
- fd1.contentQualifiedName = model.toJavaQualifiedTypeName(namespace, fd1.name, false);
- fd1.def = "null";
- // next type
- if (!visitedElements.contains(nel)) {
- elements[ptr++] = nel;
- }
- } else if (hasTextContents) {
- fd1.clType = FieldDesc.STR;
- fd1.type = "String";
- fd1.def = "null";
- } else {
- fd1.clType = FieldDesc.BOOL;
- fd1.type = "boolean";
- fd1.def = "false";
- }
- } else if (nel.content instanceof DTDContainer) {
- boolean hasAttrFields = false;
- boolean hasTextField = false;
- if ((nel.content instanceof DTDMixed) && ((DTDMixed) nel.content).getItemsVec().size() == 1) {
- hasTextField = true;
- for (Object o : nel.attributes.values()) {
- final DTDAttribute attr = (DTDAttribute) o;
- if (attr.decl != DTDDecl.FIXED && !"ID".equals(attr.type)) {
- hasAttrFields = true;
- break;
- }
- }
- }
- if (hasTextField && !hasAttrFields) {
- fd1.clType = FieldDesc.STR;
- fd1.type = "String";
- fd1.def = "null";
- } else {
- fd1.clType = FieldDesc.OBJ;
- fd1.type = model.toJavaTypeName(fd1.tagName, namespace);
- fd1.contentQualifiedName = model.toJavaQualifiedTypeName(namespace, fd1.tagName, false);
- // next type
- if (!visitedElements.contains(nel)) {
- elements[ptr++] = nel;
- }
- }
- } else {
- fd1.type = "ERROR:Name";
- }
- if ((pentry.many || n.cardinal.type >= 2) && fd1.clType != FieldDesc.BOOL) {
- fd1.elementType = fd1.type;
- fd1.elementName = fd1.name;
- fd1.type = "List<" + fd1.elementType + ">";
- fd1.name = Util.pluralize(fd1.name);
- fd1.def = "new ArrayList(0)";
- fd1.clType = -fd1.clType;
- fd1.comment = "array of " + fd1.elementType;
- }
- fd1.realIndex = td.fdMap.size();
- duplicates = Util.addToNameMap(td.fdMap, fd1, false) || duplicates;
- } else if (p instanceof DTDContainer) {
- final DTDContainer cont = (DTDContainer) p;
- final boolean isChoice = cont instanceof DTDChoice;
- // 0 - NONE, 1 - OPT, 2 - ZEROMANY, 3 - ONEMANY
- final boolean required = !isChoice && pentry.required && p.cardinal != DTDCardinal.ZEROMANY && p.cardinal != DTDCardinal.OPTIONAL;
- final boolean many = p.cardinal == DTDCardinal.ONEMANY || p.cardinal == DTDCardinal.ZEROMANY;
- List<DTDItem> l = cont.getItemsVec();
- if (!many && isChoice) {
- choiceList.add(l);
- }
- for (DTDItem aL : l) {
- plist.add(new Entry(aL, many, required));
- }
- } else {
- Util.logerr("unknown item " + p);
- }
- }
- td.duplicates = duplicates;
- td.documentation = parseDTDItemDocumentation(dtd, el, "Type " + el.name + " documentation");
- jtMap.put(model.toJavaQualifiedTypeName(namespace, td.name, false), td);
- int i = 0;
- for (FieldDesc fd : td.fdMap.values()) {
- fd.idx = i++;
- }
- for (List<DTDItem> l : choiceList) {
- ArrayList<DTDItem> clist = new ArrayList<DTDItem>();
- LinkedList<DTDItem> elist = new LinkedList<DTDItem>();
- for (i = 0; i < l.size(); i++) {
- elist.add(l.get(i));
- }
- while (!elist.isEmpty()) {
- DTDItem p = elist.removeFirst();
- if (p instanceof DTDContainer) {
- List<DTDItem> l2 = ((DTDContainer) p).getItemsVec();
- for (DTDItem aL2 : l2) {
- elist.addFirst(aL2);
- }
- } else if (p instanceof DTDName) {
- clist.add(p);
- }
- }
- boolean choiceOpt = true;
- FieldDesc[] choice = new FieldDesc[clist.size()];
- for (i = 0; i < choice.length; i++) {
- DTDName p = (DTDName) clist.get(i);
- String s = Util.toJavaFieldName(p.value);
- FieldDesc fd = td.fdMap.get(s);
- if (fd == null) {
- fd = td.fdMap.get(Util.pluralize(s));
- if (fd == null) {
- Util.logerr("uknown choice element: " + s);
- continue;
- }
- }
- choice[i] = fd;
- choice[i].choice = choice;
- if (fd.required) choiceOpt = false;
- }
- for (i = 0; i < choice.length; i++) {
- choice[i].choiceOpt = choiceOpt;
- }
- }
- }
- List<DTDEntity> entList = dtd.getItemsByType(DTDEntity.class);
- for (DTDEntity entity : entList) {
- String value = entity.value;
- if (!value.startsWith("(") || !value.endsWith(")")) {
- continue;
- }
- String typeName = model.toJavaTypeName(entity.name, namespace);
- TypeDesc td = new TypeDesc(entity.name, namespace, typeName, TypeDesc.TypeEnum.ENUM);
- StringTokenizer st = new StringTokenizer(value, "(|)");
- while (st.hasMoreTokens()) {
- final String s = st.nextToken();
- td.fdMap.put(s, new FieldDesc(Util.computeEnumConstantName(s, td.name), s));
- }
- td.documentation = parseDTDItemDocumentation(dtd, entity, "Type " + entity.name + " documentation");
- jtMap.put(model.toJavaQualifiedTypeName(namespace, td.name, true), td);
- }
- }
-
- private static String parseDTDItemDocumentation(DTD dtd, DTDOutput obj, String title) {
- int elementIndex = dtd.items.indexOf(obj);
- if (elementIndex < 1) return null;
- Object prev = dtd.items.get(elementIndex - 1);
- if (!(prev instanceof DTDComment)) return null;
- DTDComment comment = (DTDComment) prev;
- return title + "\n" + "<pre>\n" + comment.getText() + "\n</pre>";
- }
-
- static class Entry {
- boolean required;
- boolean many;
- DTDItem p;
-
- Entry(DTDItem p, boolean many, boolean required) {
- this.required = required;
- this.many = many;
- this.p = p;
- }
-
- Entry parent;
- DTDItem it;
- Vector choice;
- int num;
-
- Entry(Entry parent, DTDItem it, Vector choice, int num) {
- this.parent = parent;
- this.it = it;
- this.choice = choice;
- this.num = num;
- }
- }
-
-
- private static void checkDTDRootElement(DTD dtd) throws Exception {
- if (dtd.rootElement == null) {
- StringBuffer sb = new StringBuffer("Empty root: possible elements: ");
- HashMap map = new HashMap(dtd.elements);
- for (Object o : dtd.elements.values()) {
- DTDElement el = (DTDElement) o;
- if (el.content instanceof DTDContainer) {
- for (Object obj : ((DTDContainer) el.content).getItemsVec()) {
- if (obj instanceof DTDName) {
- map.remove(((DTDName) obj).value);
- }
- }
- }
- }
- if (dtd.rootElement != null) return;
- sb.append(map.size()).append(map.keySet());
- throw new Exception(sb.toString());
- }
- }
-
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/DomGenDialog.java b/xml/dom-impl/src/com/intellij/util/dom/generator/DomGenDialog.java
deleted file mode 100644
index 8675b6b8c5f6..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/DomGenDialog.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.dom.generator;
-
-import com.intellij.openapi.project.Project;
-import com.intellij.openapi.ui.DialogWrapper;
-
-import javax.swing.*;
-import java.io.File;
-
-/**
- * @author Konstantin Bulenkov
- */
-public class DomGenDialog extends DialogWrapper{
- final DomGenPanel panel;
- final JComponent comp;
-
- protected DomGenDialog(Project project) {
- super(project);
- panel = new DomGenPanel(project);
- comp = panel.getComponent();
- panel.restore();
- setTitle("Generate Dom Model from XSD or DTD");
- init();
- getOKAction().putValue(Action.NAME, "Generate");
- }
-
- @Override
- protected JComponent createCenterPanel() {
- return comp;
- }
-
- @Override
- protected void doOKAction() {
- if (!panel.validate()) return;
- final String location = panel.getLocation();
- ModelLoader loader = location.toLowerCase().endsWith(".xsd") ? new XSDModelLoader() : new DTDModelLoader();
- final JetBrainsEmitter emitter = new JetBrainsEmitter();
- final MergingFileManager fileManager = new MergingFileManager();
- if (panel.getAuthor().trim().length() > 0) {
- emitter.setAuthor(panel.getAuthor());
- }
- final ModelGen modelGen = new ModelGen(loader, emitter, fileManager);
- final NamespaceDesc desc = panel.getNamespaceDescriptor();
- modelGen.setConfig(desc.name, location, desc, panel.getSkippedSchemas());
- try {
- final File output = new File(panel.getOutputDir());
- modelGen.perform(output, new File(location).getParentFile());
- } catch (Exception e) {
- e.printStackTrace(System.err);
- }
- panel.saveAll();
- super.doOKAction();
- }
-
- @Override
- public void doCancelAction() {
- panel.saveAll();
- super.doCancelAction();
- }
-
- @Override
- protected String getDimensionServiceKey() {
- return getClass().getName();
- }
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/DomGenPanel.form b/xml/dom-impl/src/com/intellij/util/dom/generator/DomGenPanel.form
deleted file mode 100644
index c914572ca2e4..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/DomGenPanel.form
+++ /dev/null
@@ -1,137 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.util.dom.generator.DomGenPanel">
- <grid id="27dc6" binding="mainPanel" layout-manager="GridLayoutManager" row-count="8" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
- <margin top="0" left="0" bottom="0" right="0"/>
- <constraints>
- <xy x="20" y="20" width="424" height="262"/>
- </constraints>
- <properties/>
- <clientProperties>
- <BorderFactoryClass class="java.lang.String" value="com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent"/>
- </clientProperties>
- <border type="none" title="Dom Generator Config"/>
- <children>
- <component id="29b47" class="javax.swing.JLabel">
- <constraints>
- <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
- </constraints>
- <properties>
- <text value="Namespace:"/>
- </properties>
- </component>
- <vspacer id="e8ccd">
- <constraints>
- <grid row="7" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
- </constraints>
- </vspacer>
- <component id="f5680" class="javax.swing.JLabel">
- <constraints>
- <grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
- </constraints>
- <properties>
- <text value="Super Class:"/>
- </properties>
- </component>
- <component id="20f66" class="javax.swing.JTextField" binding="mySuperClass">
- <constraints>
- <grid row="3" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
- <preferred-size width="327" height="22"/>
- </grid>
- </constraints>
- <properties>
- <text value="com.intellij.util.xml.DomElement"/>
- </properties>
- </component>
- <component id="4a359" class="javax.swing.JLabel">
- <constraints>
- <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
- </constraints>
- <properties>
- <text value="Package:"/>
- </properties>
- </component>
- <component id="afd05" class="javax.swing.JTextField" binding="myPackage">
- <constraints>
- <grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
- <preferred-size width="327" height="22"/>
- </grid>
- </constraints>
- <properties>
- <text value="com.intellij.myFramework.model"/>
- </properties>
- </component>
- <component id="d62dc" class="javax.swing.JLabel">
- <constraints>
- <grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
- </constraints>
- <properties>
- <text value="Output Dir:"/>
- </properties>
- </component>
- <component id="6a48b" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myOutputDir" custom-create="true">
- <constraints>
- <grid row="4" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false">
- <preferred-size width="327" height="22"/>
- </grid>
- </constraints>
- <properties/>
- </component>
- <component id="7fb9d" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="mySchemaLocation" custom-create="true">
- <constraints>
- <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false">
- <preferred-size width="327" height="22"/>
- </grid>
- </constraints>
- <properties/>
- </component>
- <component id="7940e" class="javax.swing.JLabel">
- <constraints>
- <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
- </constraints>
- <properties>
- <text value="Scheme File:"/>
- </properties>
- </component>
- <component id="833b2" class="javax.swing.JTextField" binding="myNamespace">
- <constraints>
- <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
- <preferred-size width="327" height="22"/>
- </grid>
- </constraints>
- <properties/>
- </component>
- <component id="bdaaf" class="javax.swing.JLabel">
- <constraints>
- <grid row="6" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
- </constraints>
- <properties>
- <text value="Skip schemes:"/>
- </properties>
- </component>
- <component id="f4732" class="javax.swing.JTextArea" binding="mySkipSchemas">
- <constraints>
- <grid row="6" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="6" anchor="0" fill="3" indent="0" use-parent-layout="false">
- <preferred-size width="150" height="50"/>
- </grid>
- </constraints>
- <properties/>
- </component>
- <component id="54b59" class="javax.swing.JLabel">
- <constraints>
- <grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
- </constraints>
- <properties>
- <text value="@author:"/>
- </properties>
- </component>
- <component id="b033e" class="javax.swing.JTextField" binding="myAuthor">
- <constraints>
- <grid row="5" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
- <preferred-size width="150" height="-1"/>
- </grid>
- </constraints>
- <properties/>
- </component>
- </children>
- </grid>
-</form>
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/DomGenPanel.java b/xml/dom-impl/src/com/intellij/util/dom/generator/DomGenPanel.java
deleted file mode 100644
index 29d956b63586..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/DomGenPanel.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.dom.generator;
-
-import com.intellij.ide.util.PropertiesComponent;
-import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
-import com.intellij.openapi.fileChooser.FileTypeDescriptor;
-import com.intellij.openapi.project.Project;
-import com.intellij.openapi.ui.Messages;
-import com.intellij.openapi.ui.TextFieldWithBrowseButton;
-import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.openapi.vfs.LocalFileSystem;
-import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.wm.IdeFocusManager;
-import com.intellij.psi.PsiFile;
-import com.intellij.psi.PsiManager;
-import com.intellij.psi.xml.XmlAttribute;
-import com.intellij.psi.xml.XmlDocument;
-import com.intellij.psi.xml.XmlFile;
-import com.intellij.psi.xml.XmlTag;
-import com.intellij.util.ArrayUtil;
-
-import javax.swing.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.io.File;
-import java.util.ArrayList;
-
-/**
- * @author Konstantin Bulenkov
- */
-public class DomGenPanel {
- private JPanel mainPanel;
- private JTextField myNamespace;
- private JTextField mySuperClass;
- private TextFieldWithBrowseButton mySchemaLocation;
- private JTextField myPackage;
- private TextFieldWithBrowseButton myOutputDir;
- private JTextArea mySkipSchemas;
- private JTextField myAuthor;
- private final Project myProject;
-
- public DomGenPanel(Project project) {
- myProject = project;
- }
-
- private void createUIComponents() {
- mySchemaLocation = new TextFieldWithBrowseButton();
- final String title = "Choose XSD or DTD schema";
- mySchemaLocation.addBrowseFolderListener(title, "Make sure there are only necessary schemes in directory where your XSD or DTD schema is located", myProject, new FileTypeDescriptor(title, "xsd", "dtd"));
- mySchemaLocation.getTextField().setEditable(false);
- mySchemaLocation.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- final File file = new File(mySchemaLocation.getText());
- if (file.exists() && file.getName().toLowerCase().endsWith(".xsd")) {
- final VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(file);
- if (vf != null) {
- final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vf);
- if (psiFile instanceof XmlFile) {
- final XmlDocument xml = ((XmlFile)psiFile).getDocument();
- if (xml != null) {
- final XmlTag rootTag = xml.getRootTag();
- if (rootTag != null) {
- String target = null;
- ArrayList<String> ns = new ArrayList<String>();
- for (XmlAttribute attr : rootTag.getAttributes()) {
- if ("targetNamespace".equals(attr.getName())) {
- target = attr.getValue();
- }
- else if (attr.getName().startsWith("xmlns")) {
- ns.add(attr.getValue());
- }
- }
-
- ns.remove(target);
- if (target != null) {
- myNamespace.setText(target);
- }
- mySkipSchemas.setText(StringUtil.join(ArrayUtil.toStringArray(ns), "\n"));
- }
- }
- }
- }
- }
- }
- });
- myOutputDir = new TextFieldWithBrowseButton();
- myOutputDir.addBrowseFolderListener("Select Output For Generated Files", "", myProject, FileChooserDescriptorFactory.getDirectoryChooserDescriptor("Output For Generated Files"));
- }
-
- public JComponent getComponent() {
- return mainPanel;
- }
-
- public NamespaceDesc getNamespaceDescriptor() {
- return new NamespaceDesc(myNamespace.getText().trim(), myPackage.getText().trim(), mySuperClass.getText().trim(), "", null, null, null, null);
- }
-
- public String getLocation() {
- return mySchemaLocation.getText();
- }
-
- public String getOutputDir() {
- return myOutputDir.getText();
- }
-
- private static final String PREFIX = "DomGenPanel.";
- public void restore() {
- myNamespace.setText(getValue("namespace", ""));
- myPackage.setText(getValue("package", "com.intellij.myframework.model"));
- mySchemaLocation.setText(getValue("schemaLocation", ""));
- mySuperClass.setText(getValue("superClass", "com.intellij.util.xml.DomElement"));
- myOutputDir.setText(getValue("output", ""));
- mySkipSchemas.setText(getValue("skipSchemas", "http://www.w3.org/2001/XMLSchema\nhttp://www.w3.org/2001/XMLSchema-instance"));
- myAuthor.setText(getValue("author", ""));
- }
-
- private static String getValue(String name, String defaultValue) {
- return PropertiesComponent.getInstance().getOrInit(PREFIX + name, defaultValue);
- }
-
- private static void setValue(String name, String value) {
- PropertiesComponent.getInstance().setValue(PREFIX + name, value);
- }
-
- public void saveAll() {
- setValue("namespace", myNamespace.getText());
- setValue("package", myPackage.getText());
- setValue("schemaLocation", mySchemaLocation.getText());
- setValue("superClass", mySuperClass.getText());
- setValue("output", myOutputDir.getText());
- setValue("skipSchemas", mySkipSchemas.getText());
- setValue("author", myAuthor.getText());
- }
-
- public boolean validate() {
- if (!new File(mySchemaLocation.getText()).exists()) {
- Messages.showErrorDialog(myProject, "Schema location doesn't exist", "Error");
- IdeFocusManager.getInstance(myProject).requestFocus(mySchemaLocation, true);
- return false;
- }
-
- if (!new File(myOutputDir.getText()).exists()) {
- Messages.showErrorDialog(myProject, "Output dir doesn't exist", "Error");
- IdeFocusManager.getInstance(myProject).requestFocus(myOutputDir, true);
- return false;
- }
-
- return true;
- }
-
- public String[] getSkippedSchemas() {
- final String schemes = mySkipSchemas.getText().replaceAll("\r\n", "\n").trim();
- if (schemes.length() > 0) {
- return schemes.split("\n");
- }
- return new String[0];
- }
-
- public String getAuthor() {
- return myAuthor.getText();
- }
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/Emitter.java b/xml/dom-impl/src/com/intellij/util/dom/generator/Emitter.java
deleted file mode 100644
index 49f9d83d0b99..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/Emitter.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import java.io.File;
-
-/**
- * @author Konstantin Bulenkov
- */
-public interface Emitter {
- String JDOC_OPEN = "/**";
- String JDOC_CONT = " * ";
- String JDOC_CLOSE = " */";
-
- void emit(FileManager fileManager, ModelDesc model, File outputRoot);
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/FieldDesc.java b/xml/dom-impl/src/com/intellij/util/dom/generator/FieldDesc.java
deleted file mode 100644
index f7a3757cf6c9..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/FieldDesc.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-/**
- * @author Konstantin Bulenkov
- */
-public class FieldDesc implements Comparable<FieldDesc> {
- final static int STR = 1;
- final static int BOOL = 2;
- final static int OBJ = 3;
- final static int ATTR = 4;
- final static int DOUBLE = 5;
- final static int SIMPLE = 6;
-
- public FieldDesc(String name, String def) {
- this.name = name;
- this.def = def;
- }
-
- public FieldDesc(int clType, String name, String type, String elementType, String def, boolean required) {
- this.clType = clType;
- this.name = name;
- this.type = type;
- this.elementType = elementType;
- this.def = def;
- this.required = required;
- }
-
- int clType = STR;
- String name;
- String type;
- String elementType;
- String def;
- boolean required;
-
- int idx;
- String tagName;
- String elementName;
- String comment;
- FieldDesc[] choice;
- boolean choiceOpt;
-
- String documentation;
- String simpleTypesString;
- int duplicateIndex = -1;
- int realIndex;
- String contentQualifiedName;
-
- public int compareTo(FieldDesc o) {
- return name.compareTo(o.name);
- }
-
- public String toString() {
- return "Field: " + name + ";" + type + ";" + elementName + ";" + elementType;
- }
-
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/FileManager.java b/xml/dom-impl/src/com/intellij/util/dom/generator/FileManager.java
deleted file mode 100644
index 0eac71fe2a2c..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/FileManager.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import java.io.File;
-
-/**
- * @author Konstantin Bulenkov
- */
-public interface FileManager {
- public File releaseOutputFile(File outFile);
- public File getOutputFile(File target);
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/GenerateDomModelAction.java b/xml/dom-impl/src/com/intellij/util/dom/generator/GenerateDomModelAction.java
deleted file mode 100644
index ffd90a14cd9c..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/GenerateDomModelAction.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.dom.generator;
-
-import com.intellij.openapi.actionSystem.AnAction;
-import com.intellij.openapi.actionSystem.AnActionEvent;
-import com.intellij.openapi.actionSystem.PlatformDataKeys;
-import com.intellij.openapi.project.Project;
-
-/**
- * @author Konstantin Bulenkov
- */
-public class GenerateDomModelAction extends AnAction {
- @Override
- public void actionPerformed(AnActionEvent e) {
- final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext());
- if (project != null) {
- new DomGenDialog(project).show();
- }
- }
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/JetBrainsEmitter.java b/xml/dom-impl/src/com/intellij/util/dom/generator/JetBrainsEmitter.java
deleted file mode 100644
index dadb5044938f..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/JetBrainsEmitter.java
+++ /dev/null
@@ -1,679 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.*;
-
-/**
- * @author Gregory.Shrago
- * @author Konstantin Bulenkov
- */
-public class JetBrainsEmitter implements Emitter {
- static final boolean NOT_COMPARE_MODE = true; // compare mode: skip package decl & all comments/javadoc
- static final boolean JB_OFF = false;
- static final boolean REPLACE_TYPES_WITH_INTERFACES = true;
- private String AUTHOR = null;
-
-
- public void emit(FileManager fileManager, ModelDesc model, File outputRoot) {
- final NamespaceDesc nsdDef = model.nsdMap.get("");
- final Set<String> simpleTypes = new TreeSet<String>();
- for (TypeDesc td : model.jtMap.values()) {
- generateClass(fileManager, td, model, outputRoot, simpleTypes);
- }
-// for (Iterator it = nsdMap.values().iterator(); it.hasNext(); ) {
-// NamespaceDesc nsd = (NamespaceDesc) it.next();
-// generateSuper(nsd, outputRoot);
-// generateHelper(nsd, jtMap, outputRoot);
-// }
- generateSuper(fileManager, nsdDef, model, outputRoot);
- generateHelper(fileManager, nsdDef, model, outputRoot);
-
- Util.log("SimpleTypes log:");
- for (String s : simpleTypes) {
- Util.log(" " + s);
- }
- }
-
- public void generateClass(FileManager fileManager, TypeDesc td, ModelDesc model, File outDir, Set<String> simpleTypes) {
- final Map<String, TypeDesc> jtMap = model.jtMap;
- final Map<String, NamespaceDesc> nsdMap = model.nsdMap;
- final NamespaceDesc nsd = nsdMap.get(nsdMap.containsKey(td.xsNamespace) ? td.xsNamespace : "");
- final String typeName = td.name;
- final String typeQName = model.getNSDPrefix(td) + typeName;
- final String pkgName = typeQName.lastIndexOf('.') > -1 ? typeQName.substring(0, typeQName.lastIndexOf('.')) : "";
-
- final File outFile = fileManager.getOutputFile(new File(outDir, toJavaFileName(typeQName)));
- PrintWriter out = null;
- try {
- TreeSet<String> externalClasses = new TreeSet<String>();
- if (td.type != TypeDesc.TypeEnum.ENUM) {
- if (nsd.imports != null) {
- StringTokenizer st = new StringTokenizer(nsd.imports, ";");
- while (st.hasMoreTokens()) {
- externalClasses.add(st.nextToken());
- }
- }
- if (!model.getNSDPrefix("", nsd.superClass, false).equals(model.getNSDPrefix(td))) {
- externalClasses
- .add(model.getNSDPrefix("", nsd.superClass, false) + nsd.superClass.substring(nsd.superClass.lastIndexOf(".") + 1));
- }
- if (td.supers != null) {
- for (TypeDesc tds : td.supers) {
- String pkg1 = model.getNSDPrefix(tds);
- String pkg2 = model.getNSDPrefix(td);
- if (!pkg1.equals(pkg2)) {
- externalClasses.add(model.getNSDPrefix(tds) + tds.name);
- }
- }
- }
- for (FieldDesc fd : td.fdMap.values()) {
- if (fd.simpleTypesString != null && fd.simpleTypesString.indexOf(":fully-qualified-classType;") != -1) {
- externalClasses.add("com.intellij.psi.PsiClass");
- }
- if (fd.contentQualifiedName != null && fd.contentQualifiedName.indexOf('.') > 0) {
- String pkgNameFD = fd.contentQualifiedName.substring(0, fd.contentQualifiedName.lastIndexOf('.'));
- if (!pkgNameFD.equals(pkgName)) {
- externalClasses.add(fd.contentQualifiedName);
- }
- }
- if (fd.clType < 0) {
- externalClasses.add("java.util.List");
- }
- externalClasses.add("org.jetbrains.annotations.NotNull");
- externalClasses.add("com.intellij.util.xml.*");
- }
- }
-
- Util.log("Generating type: " + typeName + "..");
- out = new PrintWriter(new FileWriter(outFile));
- if (NOT_COMPARE_MODE) {
- out.println("// Generated on " + new Date());
- out.println("// DTD/Schema : " + nsd.name);
- }
- out.println("");
- if (NOT_COMPARE_MODE && pkgName != null && pkgName.length() > 0) {
- out.println("package " + pkgName + ";");
- }
- out.println();
- if (td.type != TypeDesc.TypeEnum.ENUM) {
- boolean javaLang = false;
- boolean external = false;
- for (String s : externalClasses) {
- if (s.startsWith("java.")) {
- javaLang = true;
- continue;
- }
- external = true;
- out.println("import " + s + ";");
- }
- if (javaLang) {
- if (external) out.println();
- for (String s : externalClasses) {
- if (!s.startsWith("java.")) continue;
- out.println("import " + s + ";");
- }
- }
- out.println();
- }
- if (td.type == TypeDesc.TypeEnum.ENUM) {
- boolean text = false;
- for (Map.Entry<String, FieldDesc> e : td.fdMap.entrySet()) {
- if (!e.getKey().equals(e.getValue().name)) {
- text = true;
- break;
- }
- }
- if (NOT_COMPARE_MODE) {
- out.println(JDOC_OPEN);
- out.println(JDOC_CONT + td.xsNamespace + ":" + td.xsName + " enumeration.");
- if (AUTHOR != null) out.println(JDOC_CONT + AUTHOR);
- printDocumentation(out, td.documentation, JDOC_CONT);
-
- out.println(JDOC_CLOSE);
- }
- out.print("public enum " + typeName + (text ? (JB_OFF ? "" : " implements com.intellij.util.xml.NamedEnum") : ""));
- out.print(" {");
- boolean first = true;
- for (Map.Entry<String, FieldDesc> e : td.fdMap.entrySet()) {
- String val = e.getKey();
- FieldDesc id = e.getValue();
- if (first) {
- first = false;
- out.println("");
- }
- else {
- out.println(",");
- }
- if (text) {
- out.print("\t" + id.name + " (\"" + val + "\")");
- }
- else {
- out.print("\t" + id.name);
- }
- }
- if (text) {
- out.println(";");
- out.println();
- out.println("\tprivate final String value;");
- out.println("\tprivate " + typeName + "(String value) { this.value = value; }");
- out.println("\tpublic String getValue() { return value; }");
- }
- out.println();
- out.println("}");
- return;
- }
- if (NOT_COMPARE_MODE) {
- out.println(JDOC_OPEN);
- if (td.type == TypeDesc.TypeEnum.GROUP_INTERFACE) {
- out.println(JDOC_CONT + td.xsNamespace + ":" + td.xsName + " model group interface.");
- }
- else {
- out.println(JDOC_CONT + td.xsNamespace + ":" + td.xsName + " interface.");
- }
- printDocumentation(out, td.documentation, JDOC_CONT);
- if (AUTHOR != null) out.println(JDOC_CONT + AUTHOR);
- out.println(JDOC_CLOSE);
- }
- out.print("public interface " + typeName);
- if (nsd.superClass != null || (td.supers != null && td.supers.length > 1)) {
- boolean comma = false;
- if (td.type != TypeDesc.TypeEnum.GROUP_INTERFACE) {
- if (nsd.superClass != null) {
- out.print(" extends " + nsd.superClass.substring(nsd.superClass.lastIndexOf(".") + 1));
- comma = true;
- }
- }
- if (td.supers != null && td.supers.length > 0) {
- if (!comma) out.print(" extends ");
- for (TypeDesc aSuper : td.supers) {
- if (comma) {
- out.print(", ");
- }
- else {
- comma = true;
- }
- out.print(aSuper.name);
- }
- }
- }
- out.println(" {");
-
- FieldDesc[] fields = td.fdMap.values().toArray(new FieldDesc[td.fdMap.size()]);
- if (fields.length == 0) {
- Util.logwarn("no fields in: " + td.xsName);
- }
- Arrays.sort(fields, new Comparator<FieldDesc>() {
- public int compare(FieldDesc o1, FieldDesc o2) {
- return o1.realIndex - o2.realIndex;
- }
- });
- out.println("");
- for (FieldDesc field : fields) {
- String tagName = field.tagName;
- String type = field.type;
- String elementType = field.elementType;
- String name = field.name;
- String paramName = toJavaIdName(field.clType > 0 ? name : field.elementName);
- String javaDocTagName = field.clType < 0 ? tagName + " children" : tagName != null ? tagName + " child" : "simple content";
- boolean isAttr = field.clType == FieldDesc.ATTR;
- boolean isList = field.clType < 0;
-
- if (name.equals("class")) { // getClass method prohibited
- name = "clazz";
- }
- boolean nameChanged = field.tagName != null &&
- !name
- .equals(isList ? Util.pluralize(Util.toJavaFieldName(field.tagName)) : Util.toJavaFieldName(field.tagName));
-
- // annotations
- // types replacement
- String newType = field.clType < 0 ? elementType : type;
- String converterString = null;
- if (field.simpleTypesString != null) {
- if (field.simpleTypesString.indexOf(":fully-qualified-classType;") != -1) { // localType, remoteType, etc.
- newType = "PsiClass";
- //converterString = (JB_OFF ? "//" : "")+"\t@Convert (PsiClassReferenceConverter.class)";
- }
- else if (field.simpleTypesString.indexOf(":ejb-linkType;") != -1) {
- }
- else if (field.simpleTypesString.indexOf(":ejb-ref-nameType;") != -1) { // jndi-nameType
- }
- else if (field.simpleTypesString.indexOf(":pathType;") != -1) {
- }
- else if (field.simpleTypesString.indexOf(":java-identifierType;") != -1) {
- //out.println((JB_OFF ? "//" : "") +"\t@Convert (JavaIdentifierConverter.class)");
- }
- else if (field.simpleTypesString.indexOf(":QName;") != -1) {
- // ???
- }
- else if (field.simpleTypesString.indexOf(":integer;") != -1) { // BigDecimal
- newType = REPLACE_TYPES_WITH_INTERFACES ? "Integer" : "int";
- }
- else if (field.simpleTypesString.indexOf(":int;") != -1) {
- newType = REPLACE_TYPES_WITH_INTERFACES ? "Integer" : "int";
- }
- else if (field.simpleTypesString.indexOf(":byte;") != -1) {
- newType = REPLACE_TYPES_WITH_INTERFACES ? "Byte" : "byte";
- }
- else if (field.simpleTypesString.indexOf(":short;") != -1) {
- newType = REPLACE_TYPES_WITH_INTERFACES ? "Short" : "short";
- }
- else if (field.simpleTypesString.indexOf(":long;") != -1) {
- newType = REPLACE_TYPES_WITH_INTERFACES ? "Long" : "long";
- }
- else if (field.simpleTypesString.indexOf(":float;") != -1) {
- newType = REPLACE_TYPES_WITH_INTERFACES ? "Float" : "float";
- }
- else if (field.simpleTypesString.indexOf(":double;") != -1) {
- newType = REPLACE_TYPES_WITH_INTERFACES ? "Double" : "double";
- }
- else if (field.simpleTypesString.indexOf(":boolean;") != -1) { // true-falseType
- newType = REPLACE_TYPES_WITH_INTERFACES ? "Boolean" : "boolean";
- }
- for (int idx = 0; idx != -1;) {
- simpleTypes.add(field.simpleTypesString.substring(idx));
- idx = field.simpleTypesString.indexOf(';', idx) + 1;
- if (idx == 0) break;
- }
- }
- if (REPLACE_TYPES_WITH_INTERFACES) {
- switch (Math.abs(field.clType)) {
- case FieldDesc.ATTR:
- newType = "GenericAttributeValue<" + newType + ">";
- break;
- case FieldDesc.BOOL:
- newType = "GenericDomValue<Boolean>";
- break;
- case FieldDesc.SIMPLE:
- break;
- case FieldDesc.STR:
- newType = "GenericDomValue<" + newType + ">";
- break;
- case FieldDesc.OBJ: {
- TypeDesc ftd = jtMap.get(field.contentQualifiedName);
- if (ftd != null && ftd.type == TypeDesc.TypeEnum.ENUM) {
- newType = "GenericDomValue<" + ftd.name + ">";
- }
- break;
- }
- }
- }
- if (newType != null && isList) {
- elementType = newType;
- }
- else if (newType != null) {
- type = newType;
- }
- if (isList) {
- type = "List<" + elementType + ">";
- }
-
- StringBuffer sbAnnotations = new StringBuffer();
- if (field.clType == FieldDesc.SIMPLE) {
- // sbAnnotations.append((JB_OFF ? "//" : "") +"\t@TagValue");
- }
- else if (isAttr && nameChanged) {
- sbAnnotations.append((JB_OFF ? "//" : "") + "\t@Attribute (\"").append(tagName).append("\")");
- }
- else if (isList) {
- // sbAnnotations.append((JB_OFF ? "//" : "") +"\t@SubTagList (\"" + tagName + "\")");
- if (nameChanged) {
- sbAnnotations.append((JB_OFF ? "//" : "") + "\t@SubTag (\"").append(tagName).append("\")");
- }
- else {
- if (isBadTagName(tagName)) {
- sbAnnotations.append((JB_OFF ? "//" : "") + "\t@SubTagList (\"").append(tagName).append("\")");
- }
- }
- }
- else {
- if (field.duplicateIndex >= 0) {
- sbAnnotations.append((JB_OFF ? "//" : "") + "\t@SubTag (value = \"").append(tagName).append("\", index = ")
- .append(field.duplicateIndex - 1).append(")");
- }
- else if (field.clType == FieldDesc.BOOL) {
- sbAnnotations.append((JB_OFF ? "//" : "") + "\t@SubTag (value = \"").append(tagName).append("\", indicator = true)");
- }
- else if (!name.equals(field.name)) {
- sbAnnotations.append((JB_OFF ? "//" : "") + "\t@SubTag (\"").append(tagName).append("\")");
- }
- }
- if (converterString != null) {
- sbAnnotations.append("\n").append(converterString);
- }
- if (NOT_COMPARE_MODE && td.type != TypeDesc.TypeEnum.GROUP_INTERFACE) {
- out.println("\t" + JDOC_OPEN);
- final String text;
- if (isList) {
- text = "the list of " + javaDocTagName;
- }
- else {
- text = "the value of the " + javaDocTagName;
- }
- out.println("\t" + JDOC_CONT + "Returns " + text + ".");
- printDocumentation(out, field.documentation, "\t" + JDOC_CONT);
- out.println("\t" + JDOC_CONT + "@return " + text + ".");
- out.println("\t" + JDOC_CLOSE);
- }
- out.println((JB_OFF ? "//" : "") + "\t@NotNull");
- if (td.type != TypeDesc.TypeEnum.GROUP_INTERFACE) {
- if (sbAnnotations.length() > 0) out.println(sbAnnotations);
- if (field.required) {
- out.println((JB_OFF ? "//" : "") + "\t@Required");
- }
- }
- out.print("\t");
- //out.print("public ");
- out.print(type);
- out.print(" ");
- out.print("get");
- out.print(Util.capitalize(name));
- out.println("();");
-
- final boolean genAddRemoveInsteadOfSet = true;
- if (!genAddRemoveInsteadOfSet || field.clType > 0) {
- if (field.clType == FieldDesc.SIMPLE) {
- if (NOT_COMPARE_MODE && td.type != TypeDesc.TypeEnum.GROUP_INTERFACE) {
- out.println("\t" + JDOC_OPEN);
- if (field.clType < 0) {
- out.println("\t" + JDOC_CONT + "Sets the list of " + javaDocTagName + ".");
- }
- else {
- out.println("\t" + JDOC_CONT + "Sets the value of the " + javaDocTagName + ".");
- }
- out.println("\t" + JDOC_CONT + "@param " + paramName + " the new value to set");
- out.println("\t" + JDOC_CLOSE);
- if (sbAnnotations.length() > 0) out.println(sbAnnotations);
- }
- out.print("\t");
- //out.print("public ");
- out.print("void set");
- out.print(Util.capitalize(name));
- out.print("(");
- if (field.required) {
- out.print((JB_OFF ? "" : "@NotNull "));
- }
- out.print(type);
- out.print(" ");
- out.print(paramName);
- out.println(");");
- }
- }
- else {
- if (NOT_COMPARE_MODE && td.type != TypeDesc.TypeEnum.GROUP_INTERFACE) {
- out.println("\t" + JDOC_OPEN);
- out.println("\t" + JDOC_CONT + "Adds new child to the list of " + javaDocTagName + ".");
- out.println("\t" + JDOC_CONT + "@return created child");
- out.println("\t" + JDOC_CLOSE);
- if (sbAnnotations.length() > 0) out.println(sbAnnotations);
- }
- out.print("\t");
- //out.print("public ");
- out.print(elementType + " add");
- out.print(Util.capitalize(field.elementName));
- out.println("();");
- }
-
- out.println("");
- out.println("");
- }
- out.println("}");
- }
- catch (IOException ex) {
- ex.printStackTrace();
- }
- finally {
- try {
- out.close();
- }
- catch (Exception ex) {
- }
- fileManager.releaseOutputFile(outFile);
- }
- }
-
- private static boolean isBadTagName(String tagName) {
- if (Character.isUpperCase(tagName.charAt(0))) return false;
- final char[] chars = tagName.toCharArray();
- for (int i = 1; i < chars.length; i++) {
- if (Character.isUpperCase(chars[i])) {
- return true;
- }
- }
- return false;
- }
-
- private void generateSuper(FileManager fileManager, NamespaceDesc nsd, ModelDesc model, File outDir) {
- if (nsd.superClass == null || nsd.superClass.length() == 0) return;
- final String typeName = nsd.superClass.substring(nsd.superClass.lastIndexOf(".") + 1);
- final String typeQName = model.toJavaQualifiedTypeName("", nsd.superClass, false);
- String pkgName = typeQName.substring(0, typeQName.lastIndexOf('.'));
- File outFile = new File(outDir, toJavaFileName(typeQName));
- outFile = fileManager.getOutputFile(outFile);
- PrintWriter out = null;
- try {
- Util.log("Generating type: " + typeName + "..");
- out = new PrintWriter(new FileWriter(outFile));
- out.println("// Generated on " + new Date());
- out.println("// DTD/Schema : " + nsd.name);
- out.println("");
- if (pkgName != null) {
- out.println("package " + pkgName + ";");
- }
- out.println("");
- out.println("");
- out.println(JDOC_OPEN);
- out.println(JDOC_CONT + nsd.name + " base interface.");
- if (AUTHOR != null) out.println(JDOC_CONT + AUTHOR);
- out.println(JDOC_CLOSE);
- out.print("public interface " + typeName + " ");
- out.println("{");
-
-
- out.println("}");
- }
- catch (IOException ex) {
- ex.printStackTrace();
- }
- finally {
- try {
- if (out != null) {
- out.close();
- }
- }
- catch (Exception ex) {
- }
- fileManager.releaseOutputFile(outFile);
- }
- }
-
- private void generateHelper(FileManager fileManager, NamespaceDesc nsd, ModelDesc model, File outDir) {
- final Map<String, TypeDesc> jtMap = model.jtMap;
- final Map<String, NamespaceDesc> nsdMap = model.nsdMap;
- if (nsd.helperClass == null || nsd.helperClass.length() == 0) return;
- ArrayList<TypeDesc> jtList = new ArrayList<TypeDesc>();
- for (TypeDesc td : jtMap.values()) {
- if (td.type != TypeDesc.TypeEnum.CLASS) continue;
-// if (!nsd.name.equals(td.xsNamespace)) {
-// continue;
-// }
- jtList.add(td);
- }
- if (jtList.size() == 0) return;
-
- String typeName = nsd.helperClass.substring(nsd.helperClass.lastIndexOf(".") + 1);
- final String typeQName = model.toJavaQualifiedTypeName("", nsd.helperClass, false);
- String pkgName = typeQName.substring(0, typeQName.lastIndexOf('.'));
- File outFile = new File(outDir, toJavaFileName(typeQName));
- outFile = fileManager.getOutputFile(outFile);
- PrintWriter out = null;
- try {
- Util.log("Generating type: " + typeName + "..");
- out = new PrintWriter(new FileWriter(outFile));
- out.println("// Generated on " + new Date());
- out.println("// DTD/Schema : " + nsd.name);
- out.println("");
- if (pkgName != null) {
- out.println("package " + pkgName + ";");
- }
- out.println("");
- out.println("");
- out.println(JDOC_OPEN);
- out.println(JDOC_CONT + nsd.name + " helper class.");
- if (AUTHOR != null) out.println(JDOC_CONT + AUTHOR);
- out.println(JDOC_CLOSE);
- out.print("public class " + typeName + " ");
- out.println("{");
- out.println("");
- out.println("\tprivate interface GetName { String getName(Object o); }");
- out.println("\tprivate static java.util.HashMap<Class, GetName> nameMap = new java.util.HashMap();");
- out.println("\tstatic {");
-
- for (TypeDesc td : jtList) {
- ArrayList<FieldDesc> fields = new ArrayList<FieldDesc>(td.fdMap.values());
- Collections.sort(fields, new Comparator<FieldDesc>() {
- public int compare(FieldDesc o1, FieldDesc o2) {
- return o1.realIndex - o2.realIndex;
- }
- });
- int guessPriority = 0;
- FieldDesc guessedField = null;
- for (FieldDesc fd : fields) {
- if (fd.clType == FieldDesc.STR || fd.clType == FieldDesc.SIMPLE || fd.clType == FieldDesc.ATTR) {
- if (fd.name.equals("name") && guessPriority < 10) {
- guessPriority = 10;
- guessedField = fd;
- }
- else if (fd.name.endsWith("Name")) {
- if ((fd.name.endsWith(Util.decapitalize(td.name + "Name")) || fd.realIndex < 2) && guessPriority < 10) {
- guessPriority = 10;
- guessedField = fd;
- }
- else if (fd.name.endsWith(Util.decapitalize("DisplayName")) && guessPriority < 5) {
- guessPriority = 5;
- guessedField = fd;
- }
- else if (guessPriority < 3) {
- guessPriority = 3;
- guessedField = fd;
- }
- }
- else if (fd.name.equals("value") && guessPriority < 1) {
- guessPriority = 1;
- guessedField = fd;
- }
- }
- else if ((fd.clType == -FieldDesc.OBJ || fd.clType == -FieldDesc.STR) && fd.name.endsWith("displayNames") && guessPriority < 5) {
- guessPriority = 5;
- guessedField = fd;
- }
- }
- out.println();
- String qname = model.getNSDPrefix(td) + td.name;
- String tdNameString = "\"" + toPresentationName(td.name) + "\"";
- out.println("\t\tnameMap.put(" + qname + ".class, new GetName() {");
- out.println("\t\t\tpublic String getName(Object o) {");
- if (guessedField != null) {
- out.println("\t\t\t\t" + qname + " my = (" + qname + ") o;");
- String getter = "my.get" + Util.capitalize(guessedField.name) + "()";
- if (guessedField.clType > 0) {
- out.println("\t\t\t\tString s = o==null? null:" + getter +
- (guessedField.clType == FieldDesc.STR || guessedField.clType == FieldDesc.ATTR ? ".getValue();" : ";"));
- out.println("\t\t\t\treturn s==null?" + tdNameString + ":s;");
- }
- else {
- out.println("\t\t\t\treturn (o!=null && " + getter + "!=null && " + getter + ".size()>0)?");
- out.println("\t\t\t\t\tgetPresentationName(" + getter + ".get(0), null):" + tdNameString + ";");
- }
- }
- else {
- out.println("\t\t\t\treturn " + tdNameString + ";");
- }
- out.println("\t\t\t}");
- out.println("\t\t});");
- }
- out.println("\t}");
-
- out.println("\tpublic static String getPresentationName(Object o, String def) {");
- out.println("\t\tGetName g = o!=null? nameMap.get(o.getClass().getInterfaces()[0]):null;");
- out.println("\t\treturn g != null?g.getName(o):def;");
- out.println("\t}");
- out.println("}");
- }
- catch (IOException ex) {
- ex.printStackTrace();
- }
- finally {
- try {
- out.close();
- }
- catch (Exception ex) {
- }
- fileManager.releaseOutputFile(outFile);
- }
- }
-
- public static void printDocumentation(PrintWriter out, String str, String prefix) {
- if (str == null) return;
- StringTokenizer st = new StringTokenizer(str, "\n\r");
- while (st.hasMoreTokens()) {
- String line = prefix + st.nextToken();
- out.println(line);
- }
- }
-
- public static String toPresentationName(String typeName) {
- StringBuffer sb = new StringBuffer(typeName.length() + 10);
- boolean prevUp = true;
- for (int i = 0; i < typeName.length(); i++) {
- char c = typeName.charAt(i);
- if (Character.isUpperCase(c) && !prevUp) {
- sb.append(' ');
- }
- sb.append(c);
- prevUp = Character.isUpperCase(c);
- }
- return sb.toString();
- }
-
- private static String toJavaFileName(String typeName) {
- return typeName.replace('.', File.separatorChar) + ".java";
- }
-
- public static String toJavaIdName(String javaFieldName) {
- if (Util.RESERVED_NAMES_MAP.containsKey(javaFieldName)) {
- javaFieldName += "_";
- }
- return javaFieldName;
- }
-
-
- public void setAuthor(String author) {
- AUTHOR = "@author " + author;
- }
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/Main.java b/xml/dom-impl/src/com/intellij/util/dom/generator/Main.java
deleted file mode 100644
index 4f8431743325..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/Main.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import java.io.File;
-
-/**
- * @author Gregory.Shrago
- * @author Konstantin Bulenkov
- */
-public class Main {
-
-
- public static void main(String argv[]) throws Exception {
- if (argv.length != 4) {
- System.out.println("Usage: Main <XSD or DTD> <input folder> <output folder> <config xml>");
- }
- String mode = argv[0];
- final ModelLoader loader;
- if (mode.equalsIgnoreCase("xsd")) {
- loader = new XSDModelLoader();
- }
- else if (mode.equalsIgnoreCase("dtd")) {
- loader = new DTDModelLoader();
- }
- else {
- System.out.println("'"+mode+"' format not supported");
- System.exit(-1);
- return;
- }
- final File modelRoot = new File(argv[1]);
- final File outputRoot = new File(argv[2]);
- final File configXml = new File(argv[3]);
-
- outputRoot.mkdirs();
- final ModelGen modelGen = new ModelGen(loader);
- modelGen.loadConfig(configXml);
- modelGen.perform(outputRoot, modelRoot);
- }
-
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/MergingFileManager.java b/xml/dom-impl/src/com/intellij/util/dom/generator/MergingFileManager.java
deleted file mode 100644
index ac2ea3179d9b..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/MergingFileManager.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import com.intellij.util.ArrayUtil;
-
-import java.io.*;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.TreeSet;
-
-/**
- * @author Gregory.Shrago
- * @author Konstantin Bulenkov
- */
-public class MergingFileManager implements FileManager {
-
- public File getOutputFile(File target) {
- File outFile = target;
- if (!outFile.getParentFile().exists() && !outFile.getParentFile().mkdirs()) {
- Util.logerr("parent mkdirs failed: " + outFile);
- return null;
- }
- for (int i = 0; outFile.exists(); i++) {
- outFile = new File(target.getParentFile(), target.getName() + ".tmp." + i);
- }
- return outFile;
- }
-
- public File releaseOutputFile(File outFile) {
- int idx = outFile.getName().indexOf(".tmp.");
- File target = outFile;
- if (idx > -1) {
- target = new File(outFile.getParentFile(), outFile.getName().substring(0, idx));
- String[] curLines = loadFile(outFile);
- String[] prevLines = loadFile(target);
- String[] mergedLines = mergeLines(curLines, prevLines);
- if (mergedLines != prevLines) {
- if (mergedLines == curLines) {
- if (target.exists() && !target.delete()) {
- Util.logerr("file replace failed: " + target);
- outFile.delete();
- } else {
- outFile.renameTo(target);
- Util.logwarn("file replaced: " + target);
- }
- } else {
- outFile.delete();
- if (target.exists() && !target.delete()) {
- Util.logerr("file replace failed: " + target);
- } else {
- writeFile(target, mergedLines);
- Util.logwarn("file merged: " + target);
- }
- }
- } else {
- outFile.delete();
- }
- }
- return target;
- }
-
- private static String[] mergeLines(String[] curLines, String[] prevLines) {
- if (prevLines.length == 0) return curLines;
- ArrayList<String> merged = new ArrayList<String>();
- int curIdx = 0, prevIdx = 0;
- String cur, prev;
- boolean classScope = false;
- boolean importMerged = false;
- for (int i = 0; i < Math.max(curLines.length, prevLines.length); i++) {
- cur = curIdx < curLines.length ? curLines[curIdx] : "";
- prev = prevIdx < prevLines.length ? prevLines[prevIdx] : "";
- if (classScope) {
- merged.addAll(Arrays.asList(curLines).subList(curIdx, curLines.length));
- break;
- } else if (prev.trim().startsWith("import ") || cur.trim().startsWith("import ")) {
- if (importMerged) continue;
- importMerged = true;
- int[] indices = new int[]{curIdx, prevIdx};
- mergeImports(merged, curLines, prevLines, indices);
- curIdx = indices[0];
- prevIdx = indices[1];
- } else if (cur.equals(prev)) {
- if (cur.trim().startsWith("public interface ")
- || cur.trim().startsWith("public enum ")) classScope = true;
- merged.add(cur);
- curIdx++;
- prevIdx++;
- } else if (prev.trim().startsWith("@")) {
- merged.add(prev);
- prevIdx++;
- } else if (cur.trim().startsWith("@")) {
- merged.add(cur);
- curIdx++;
- } else if (cur.trim().startsWith("package ") && prev.trim().startsWith("package ")) {
- merged.add(prev);
- curIdx++;
- prevIdx++;
- } else if (cur.trim().startsWith("public interface ") && prev.trim().startsWith("public interface ")) {
- classScope = true;
- prevIdx = addAllStringsUpTo(merged, prevLines, prevIdx, "{");
- curIdx = addAllStringsUpTo(null, curLines, curIdx, "{");
- } else if (cur.trim().startsWith("* ")) {
- curIdx = addAllStringsUpTo(merged, curLines, curIdx, "*/");
- if (prev.trim().startsWith("* ") || prev.trim().endsWith("*/")) {
- prevIdx = addAllStringsUpTo(null, prevLines, prevIdx, "*/");
- }
- } else {
- merged.add(cur);
- curIdx++;
- prevIdx++;
- }
- }
- String[] mergedLines = ArrayUtil.toStringArray(merged);
- if (compareLines(mergedLines, prevLines, 2) == 0) {
- return prevLines;
- } else if (compareLines(mergedLines, curLines, 2) == 0) {
- return curLines;
- } else {
- return mergedLines;
- }
- }
-
- private static void mergeImports(ArrayList<String> merged, String[] curLines, String[] prevLines, int[] indices) {
- TreeSet<String> externalClasses = new TreeSet<String>();
- for (int i = 0; i < curLines.length; i++) {
- String line = curLines[i].trim();
- if (line.startsWith("import ") && line.endsWith(";")) {
- indices[0] = i + 1;
- final String name = line.substring("import ".length(), line.length() - 1).trim();
- if (name.endsWith("*")) continue;
- externalClasses.add(name);
- }
- }
- for (int i = 0; i < prevLines.length; i++) {
- String line = prevLines[i].trim();
- if (line.startsWith("import ") && line.endsWith(";")) {
- indices[1] = i + 1;
- final String name = line.substring("import ".length(), line.length() - 1).trim();
- if (name.endsWith("*")) continue;
- externalClasses.add(name);
- }
- }
- boolean javaLang = false;
- for (String s : externalClasses) {
- if (s.startsWith("java.")) {
- javaLang = true;
- continue;
- }
- merged.add("import " + s + ";");
- }
- if (javaLang) {
- merged.add("");
- for (String s : externalClasses) {
- if (!s.startsWith("java.")) continue;
- merged.add("import " + s + ";");
- }
- }
- }
-
- private static int addAllStringsUpTo(ArrayList<String> merged, String[] lines, int startIdx, String upTo) {
- String str;
- do {
- str = startIdx < lines.length ? lines[startIdx] : upTo;
- if (merged != null) merged.add(str);
- startIdx++;
- } while (!str.trim().endsWith(upTo) && startIdx < lines.length);
- return startIdx;
- }
-
- private static int compareLines(String[] mergedLines, String[] curLines, int start) {
- if (mergedLines.length < curLines.length) return -1;
- if (mergedLines.length > curLines.length) return 1;
- for (int i = start; i < mergedLines.length; i++) {
- final int comp = mergedLines[i].compareTo(curLines[i]);
- if (comp != 0) return comp;
- }
- return 0;
- }
-
-
- private static void writeFile(File target, String[] mergedLines) {
- PrintWriter out = null;
- try {
- int lineCount = mergedLines.length;
- while (lineCount > 0 && mergedLines[lineCount - 1].length() == 0) lineCount--;
- out = new PrintWriter(new FileWriter(target));
- for (int i = 0; i < lineCount; i++) {
- String mergedLine = mergedLines[i];
- out.println(mergedLine);
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- } finally {
- if (out != null) {
- try {
- out.close();
- } catch (Exception e) {
- }
- }
- }
- }
-
-
- private static String[] loadFile(File f1) {
- if (!f1.exists()) return ArrayUtil.EMPTY_STRING_ARRAY;
- ArrayList<String> list = new ArrayList<String>();
- BufferedReader in = null;
- try {
- in = new BufferedReader(new FileReader(f1));
- String str;
- while ((str = in.readLine()) != null) {
- list.add(str);
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- }
- }
- }
- return ArrayUtil.toStringArray(list);
- }
-
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/ModelDesc.java b/xml/dom-impl/src/com/intellij/util/dom/generator/ModelDesc.java
deleted file mode 100644
index e7c41f56bad8..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/ModelDesc.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import org.apache.xerces.xs.XSObject;
-
-import javax.xml.namespace.QName;
-import java.io.PrintWriter;
-import java.util.*;
-
-/**
- * @author Gregory.Shrago
- * @author Konstantin Bulenkov
- */
-public class ModelDesc {
- final Map<String, String> name2replaceMap = new HashMap<String, String>();
- final Map<QName, String> qname2FileMap = new HashMap<QName, String>();
- final Map<String, NamespaceDesc> nsdMap = new HashMap<String, NamespaceDesc>();
- final Map<String, TypeDesc> jtMap = new TreeMap<String, TypeDesc>();
-
-
- public String getNSDPrefix(TypeDesc td) {
- return getNSDPrefix(td.xsNamespace, td.name, td.type == TypeDesc.TypeEnum.ENUM);
- }
-
- public String getNSDPrefix(String namespace, String name, boolean isEnum) {
- final int lastIdx = name.lastIndexOf(".");
- if (lastIdx > -1) return name.substring(0, lastIdx + 1);
- final NamespaceDesc nsd = getNSD(namespace);
- if (isEnum && nsd.enumPkg != null) {
- return nsd.enumPkg + ".";
- }
- if (nsd.pkgNames != null) {
- final QName qname = new QName(namespace, name);
- final String files = qname2FileMap.get(qname);
- if (files != null) {
- for (int i = 0; i < nsd.pkgNames.length; i += 2) {
- String file = nsd.pkgNames[i];
- String pkg = nsd.pkgNames[i + 1];
- if (files.contains(":" + file + ":")) {
- return pkg + ".";
- }
- }
- }
- }
- return nsd.pkgName != null && nsd.pkgName.length() > 0 ? nsd.pkgName + "." : "";
- }
-
- public NamespaceDesc getNSD(String namespace) {
- NamespaceDesc nsd = nsdMap.get(namespace);
- if (nsd == null) {
- nsd = nsdMap.get("");
- }
- return nsd;
- }
-
-
- public String toJavaTypeName(String tname, String ns) {
- final int lastIndex = tname.lastIndexOf('.');
- String xmlName = lastIndex>-1? tname.substring(lastIndex+1): tname;
- NamespaceDesc nsd = getNSD(ns);
- if (ns == null || !ns.endsWith(".dtd")) {
- if (xmlName.endsWith(Util.ANONYMOUS_ELEM_TYPE_SUFFIX)) xmlName = xmlName.substring(0, xmlName.length() - Util.ANONYMOUS_ELEM_TYPE_SUFFIX.length());
- else if (xmlName.endsWith(Util.ANONYMOUS_ATTR_TYPE_SUFFIX)) xmlName = xmlName.substring(0, xmlName.length() - Util.ANONYMOUS_ATTR_TYPE_SUFFIX.length());
- else if (xmlName.endsWith(Util.TYPE_SUFFIX)) xmlName = xmlName.substring(0, xmlName.length() - Util.TYPE_SUFFIX.length());
- }
- String rc = Util.capitalize(Util.toJavaName(xmlName));
- if (nsd.prefix != null && nsd.prefix.length()>0 && !rc.startsWith(nsd.prefix)) {
- rc = nsd.prefix + rc;
- }
- if (Util.RESERVED_NAMES_MAP.containsKey(rc)) {
- rc = Util.RESERVED_NAMES_MAP.get(rc);
- }
- if (name2replaceMap.containsKey(rc)) {
- rc = Util.expandProperties(name2replaceMap.get(rc), nsd.props);
- }
-
- return rc;
- }
-
- public String toJavaQualifiedTypeName(XSObject xs, Map<String, NamespaceDesc> nsdMap, boolean isEnum) {
- String typeName = toJavaTypeName(xs.getName(), xs.getNamespace());
- return getNSDPrefix(xs.getNamespace(), xs.getName(), isEnum) + typeName;
- }
-
- public String toJavaQualifiedTypeName(String namespace, String xmlname, boolean isEnum) {
- return getNSDPrefix(namespace, xmlname, isEnum) + toJavaTypeName(xmlname, namespace);
- }
-
- void dump(final PrintWriter out) {
-// out.println("-- qname2FileMap ---");
-// out.println(qname2FileMap);
- out.println("-- nsdMap ---");
- for (Map.Entry<String, NamespaceDesc> entry : nsdMap.entrySet()) {
- out.println("namespace key: "+entry.getKey());
- dumpNamespace(entry.getValue(), out);
- }
- out.println("-- jtMap ---");
- for (Map.Entry<String, TypeDesc> entry : jtMap.entrySet()) {
- out.println("type key: "+entry.getKey());
- dumpTypeDesc(entry.getValue(), out);
- }
- }
-
- private void dumpTypeDesc(TypeDesc td, PrintWriter out) {
- final ArrayList<String> superList;
- if (td.supers !=null) {
- superList = new ArrayList<String>();
- for (TypeDesc aSuper : td.supers) {
- superList.add(getNSDPrefix(aSuper)+aSuper.name);
- }
- } else superList = null;
- out.println(" name " + td.name);
- out.println(" type " + td.type);
- out.println(" xsName " + td.xsName);
- out.println(" xsNS " + td.xsNamespace);
- out.println(" dups " + td.duplicates);
- out.println(" supers " + (superList!=null?superList:"null"));
- out.println(" doc " + (td.documentation != null ? td.documentation.length() : "null"));
- for (Map.Entry<String, FieldDesc> entry : td.fdMap.entrySet()) {
- out.println(" field key: " + entry.getKey());
- dumpFieldDesc(td, entry.getValue(), out);
- }
- }
-
- private void dumpFieldDesc(TypeDesc td, FieldDesc fd, PrintWriter out) {
- out.println(" name " + fd.name);
- if (td.type == TypeDesc.TypeEnum.ENUM) return;
- out.println(" clType " + fd.clType);
- out.println(" required " + fd.required);
- out.println(" index " + fd.idx+"/"+fd.realIndex);
- out.println(" choiceOpt " + fd.choiceOpt);
- out.println(" choice " + (fd.choice!=null?fd.choice.length:"null"));
- out.println(" content " + fd.contentQualifiedName);
- out.println(" dupIdx " + fd.duplicateIndex);
- out.println(" elName " + fd.elementName);
- out.println(" elType " + fd.elementType);
- out.println(" def " + fd.def);
- out.println(" doc " + (fd.documentation != null? fd.documentation.length(): "null"));
- }
-
- private void dumpNamespace(NamespaceDesc value, PrintWriter out) {
- if (value.skip) return;
- out.println(" name "+value.name);
- out.println(" prefix "+value.prefix);
- out.println(" pkgName "+value.pkgName);
- out.println(" pkgNames "+(value.pkgNames != null?Arrays.asList(value.pkgNames):"null"));
- out.println(" enumPkg "+value.enumPkg);
- out.println(" super "+value.superClass);
- }
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/ModelGen.java b/xml/dom-impl/src/com/intellij/util/dom/generator/ModelGen.java
deleted file mode 100644
index e5625b3f3c13..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/ModelGen.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.dom.generator;
-
-import com.intellij.util.ArrayUtil;
-import com.intellij.util.containers.ContainerUtil;
-import org.apache.xerces.xni.XMLResourceIdentifier;
-import org.apache.xerces.xni.XNIException;
-import org.apache.xerces.xni.parser.XMLEntityResolver;
-import org.apache.xerces.xni.parser.XMLInputSource;
-import org.jdom.Document;
-import org.jdom.Element;
-import org.jdom.input.SAXBuilder;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-import java.io.CharArrayReader;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Gregory.Shrago
- * @author Konstantin Bulenkov
- */
-public class ModelGen {
- private final ModelDesc model = new ModelDesc();
- private final Map<String, String> schemaLocationMap = new HashMap<String, String>();
- private final ModelLoader loader;
- private final Emitter emitter;
- private final FileManager fileManager;
-
-
- public ModelGen(ModelLoader loader) {
- this(loader, new JetBrainsEmitter(), new MergingFileManager());
- }
-
- public ModelGen(ModelLoader loader, Emitter emitter, FileManager fileManager) {
- this.loader = loader;
- this.emitter = emitter;
- this.fileManager = fileManager;
- }
-
- public ModelDesc getModel() {
- return model;
- }
-
- public static Element loadXml(File configXml) throws Exception {
- SAXBuilder saxBuilder = new SAXBuilder();
- saxBuilder.setEntityResolver(new EntityResolver() {
- public InputSource resolveEntity(String publicId,
- String systemId)
- throws SAXException, IOException {
- return new InputSource(new CharArrayReader(new char[0]));
- }
- });
- final Document document = saxBuilder.build(configXml);
- return document.getRootElement();
- }
-
- public void loadConfig(File configXml) throws Exception {
- loadConfig(loadXml(configXml));
- }
-
- public void setConfig(String schema, String location, NamespaceDesc desc, String... schemasToSkip) {
- schemaLocationMap.put(schema, location);
- for (String sch : schemasToSkip) {
- if (sch != null && sch.length() > 0) {
- model.nsdMap.put(sch, new NamespaceDesc(sch));
- }
- }
- model.nsdMap.put("", new NamespaceDesc("", "", "com.intellij.util.xml.DomElement", "", null, null, null, null));
- model.nsdMap.put(desc.name, desc);
- }
-
- public void loadConfig(Element element) {
- final Element namespaceEl = element.getChild("namespaces");
- for (Element e : (List<Element>) namespaceEl.getChildren("schemaLocation")) {
- final String name = e.getAttributeValue("name");
- final String file = e.getAttributeValue("file");
- schemaLocationMap.put(name, file);
- }
- for (Element e : (List<Element>) namespaceEl.getChildren("reserved-name")) {
- final String name = e.getAttributeValue("name");
- final String replacement = e.getAttributeValue("replace-with");
- model.name2replaceMap.put(name, replacement);
- }
- NamespaceDesc def = new NamespaceDesc("", "generated", "java.lang.Object", "", null, null, null, null);
- for (Element nsElement : (List<Element>) namespaceEl.getChildren("namespace")) {
- final String name = nsElement.getAttributeValue("name");
- final NamespaceDesc nsDesc = new NamespaceDesc(name, def);
-
- final String skip = nsElement.getAttributeValue("skip");
- final String prefix = nsElement.getAttributeValue("prefix");
- final String superC = nsElement.getAttributeValue("super");
- final String imports = nsElement.getAttributeValue("imports");
- final String packageS = nsElement.getAttributeValue("package");
- final String packageEnumS = nsElement.getAttributeValue("enums");
- final String interfaces = nsElement.getAttributeValue("interfaces");
- final ArrayList<String> list = new ArrayList<String>();
- for (Element pkgElement : (List<Element>) nsElement.getChildren("package")) {
- final String pkgName = pkgElement.getAttributeValue("name");
- final String fileName = pkgElement.getAttributeValue("file");
- list.add(fileName);
- list.add(pkgName);
- }
- for (Element pkgElement : (List<Element>) nsElement.getChildren("property")) {
- final String propertyName = pkgElement.getAttributeValue("name");
- final String propertyValue = pkgElement.getAttributeValue("value");
- nsDesc.props.put(propertyName, propertyValue);
- }
-
- if (skip != null) nsDesc.skip = skip.equalsIgnoreCase("true");
- if (prefix != null) nsDesc.prefix = prefix;
- if (superC != null) nsDesc.superClass = superC;
- if (imports != null) nsDesc.imports = imports;
- if (packageS != null) nsDesc.pkgName = packageS;
- if (packageEnumS != null) nsDesc.enumPkg = packageEnumS;
- if (interfaces != null) nsDesc.intfs = interfaces;
- if (!list.isEmpty()) nsDesc.pkgNames = ArrayUtil.toStringArray(list);
- if (name.length() == 0) def = nsDesc;
- model.nsdMap.put(name, nsDesc);
- }
- }
-
- public void perform(final File outputRoot, final File... modelRoots) throws Exception {
- loadModel(modelRoots);
- emitter.emit(fileManager, model, outputRoot);
-
- Util.log("Done.");
- }
-
- public void loadModel(final File... modelRoots) throws Exception {
- XMLEntityResolver resolver = new XMLEntityResolver() {
- public XMLInputSource resolveEntity(XMLResourceIdentifier xmlResourceIdentifier) throws XNIException, IOException {
- String esid = xmlResourceIdentifier.getExpandedSystemId();
- if (esid == null) {
- final String location = schemaLocationMap.get(xmlResourceIdentifier.getNamespace());
- if (location != null) {
- esid = location;
- } else {
- return null;
- }
- }
- // Util.log("resolving "+esid);
- File f = null;
- for (File root : modelRoots) {
- if (root == null) continue;
- if (root.isDirectory()) {
- final String fileName = esid.substring(esid.lastIndexOf('/') + 1);
- f = new File(root, fileName);
- } else {
- f = root;
- }
- }
- if (f == null || !f.exists()) {
- Util.logerr("unable to resolve: " + esid);
- return null;
- }
- esid = f.getPath();
- return new XMLInputSource(null, esid, null);
- }
- };
- ArrayList<File> files = new ArrayList<File>();
- for (File root : modelRoots) {
- ContainerUtil.addAll(files, root.listFiles());
- }
- loader.loadModel(model, files, resolver);
- Util.log(model.jtMap.size() + " java types loaded");
- }
-
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/ModelLoader.java b/xml/dom-impl/src/com/intellij/util/dom/generator/ModelLoader.java
deleted file mode 100644
index 2e5d11859cbb..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/ModelLoader.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.dom.generator;
-
-import org.apache.xerces.xni.parser.XMLEntityResolver;
-
-import java.io.File;
-import java.util.Collection;
-
-/**
- * @author Konstantin Bulenkov
- */
-public interface ModelLoader {
- void loadModel(ModelDesc model, Collection<File> files, XMLEntityResolver resolver) throws Exception;
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/NamespaceDesc.java b/xml/dom-impl/src/com/intellij/util/dom/generator/NamespaceDesc.java
deleted file mode 100644
index 8f24825e322b..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/NamespaceDesc.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import java.util.Map;
-import java.util.HashMap;
-
-/**
- * @author Konstantin Bulenkov
- */
-public class NamespaceDesc {
- public NamespaceDesc(String name,
- String pkgName,
- String superClass,
- String prefix,
- String factoryClass,
- String helperClass,
- String imports,
- String intfs) {
- this.name = name;
- this.pkgName = pkgName;
- this.superClass = superClass;
- this.prefix = prefix;
- this.factoryClass = factoryClass;
- this.helperClass = helperClass;
- this.imports = imports;
- this.intfs = intfs;
- }
-
- public NamespaceDesc(String name) {
- this(name, "generated", "java.lang.Object", "", null, null, null, null);
- skip = true;
- }
-
-
- public NamespaceDesc(String name, NamespaceDesc def) {
- this.name = name;
- this.pkgName = def.pkgName;
- this.superClass = def.superClass;
- this.prefix = def.prefix;
- this.factoryClass = def.factoryClass;
- this.helperClass = def.helperClass;
- this.imports = def.imports;
- this.intfs = def.intfs;
- }
-
- final Map<String, String> props = new HashMap<String, String>();
- final String name;
- String pkgName;
- String superClass;
- String prefix;
- String factoryClass;
- String helperClass;
- String imports;
- String intfs;
- boolean skip;
- String[] pkgNames;
- String enumPkg;
-
-
- public String toString() {
- return "NS:"+name+" "+(skip?"skip":"")+pkgName;
- }
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/TypeDesc.java b/xml/dom-impl/src/com/intellij/util/dom/generator/TypeDesc.java
deleted file mode 100644
index f51e71a14447..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/TypeDesc.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import java.util.Map;
-import java.util.TreeMap;
-
-/**
- * @author Konstantin Bulenkov
- */
-public class TypeDesc {
- public enum TypeEnum {
- CLASS, ENUM, GROUP_INTERFACE
- }
-
- public TypeDesc(String xsName, String xsNamespace, String name, TypeEnum type) {
- this.xsName = xsName;
- this.xsNamespace = xsNamespace;
- this.name = name;
- this.type = type;
- }
-
- TypeEnum type;
- final String xsName;
- final String xsNamespace;
- final String name;
- final Map<String, FieldDesc> fdMap = new TreeMap<String, FieldDesc>();
- boolean duplicates;
- String documentation;
- TypeDesc[] supers;
-
- public String toString() {
- return (type == TypeEnum.ENUM ? "enum" : "type") + ": " + name + ";" + xsName + ";";
- }
-}
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/Util.java b/xml/dom-impl/src/com/intellij/util/dom/generator/Util.java
deleted file mode 100644
index 918010704fbe..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/Util.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import org.apache.xerces.xs.XSObject;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-
-/**
- * @author Konstantin Bulenkov
- */
-public class Util {
- public static final String ANONYMOUS_ELEM_TYPE_SUFFIX = "ElemType";
- public static final String ANONYMOUS_ATTR_TYPE_SUFFIX = "AttrType";
- public static final String TYPE_SUFFIX = "Type";
-
- //
- // Constants
- //
- public static final String XSD_NS = "http://www.w3.org/2001/XMLSchema";
-
- // reserved names map
- public static final String[] RESERVED_NAMES_TABLE = {
- "abstract", "default", "if", "private", "this",
- "boolean", "do", "implements", "protected", "throw",
- "break", "double", "import", "public", "throws",
- "byte", "else", "instanceof", "return", "transient",
- "case", "extends", "int", "short", "try",
- "catch", "final", "interface", "static", "void",
- "char", "finally", "long", "strictfp", "volatile",
- "class", "float", "native", "super", "while",
- "const", "for", "new", "switch",
- "continue", "goto", "package", "synchronized"
- };
- public static final HashMap<String, String> RESERVED_NAMES_MAP;
-
- static {
- RESERVED_NAMES_MAP = new HashMap<String, String>();
- for (String aRESERVED_NAMES_TABLE : RESERVED_NAMES_TABLE) {
- // RESERVED_NAMES_MAP.put(RESERVED_NAMES_TABLE[i], RESERVED_NAMES_TABLE[i]+"_");
- // as far as there is no actual field but setters/getters:
- RESERVED_NAMES_MAP.put(aRESERVED_NAMES_TABLE, aRESERVED_NAMES_TABLE);
- }
- //RESERVED_NAMES_MAP.put("class", "clazz");
- }
-
-
- static void log(String str) {
- System.out.println(str);
- }
-
- static void logwarn(String str) {
- System.out.println("[warn] " + str);
- }
-
- static void logerr(String str) {
- System.out.println("[error] " + str);
- }
-
- public static String pluralize(String suggestion) {
- // return suggestion+"List";
- final String VOWELS = "aeiouy";
- if (suggestion.endsWith("s") || suggestion.endsWith("x") ||
- suggestion.endsWith("ch")) {
- suggestion += "es";
- } else {
- int len = suggestion.length();
- if (suggestion.endsWith("y") && len > 1 && VOWELS.indexOf(suggestion.charAt(len - 2)) < 0) {
- suggestion = suggestion.substring(0, len - 1) + "ies";
- } else {
- suggestion += "s";
- }
- }
- return suggestion;
- }
-
- public static String toJavaFieldName(String xmlName) {
- String rc = toJavaName(xmlName);
- if (RESERVED_NAMES_MAP.containsKey(rc)) {
- rc = RESERVED_NAMES_MAP.get(rc);
- }
- return rc;
- }
-
-
- public static String computeEnumConstantName(String val, String typeName) {
- String id = val;
- for (int i = 1; i < id.length(); i++) {
- if (Character.isUpperCase(id.charAt(i))
- && Character.isLowerCase(id.charAt(i - 1))) {
- id = id.substring(0, i) + "_" + id.substring(i);
- i++;
- }
- }
- id = id.toUpperCase();
- id = id.replace('.', '_').replace('-', '_');
- if (id.length() < 2 || !Character.isJavaIdentifierStart(id.charAt(0))) {
- id = typeName + "_" + id;
- }
- return id;
- }
-
-
- public static String capitalize(String str) {
- return Character.toUpperCase(str.charAt(0)) + str.substring(1);
- }
-
- public static String decapitalize(String str) {
- return Character.toLowerCase(str.charAt(0)) + str.substring(1);
- }
-
- public static String toJavaName(String xmlName) {
- xmlName = xmlName.substring(xmlName.lastIndexOf(':') + 1);
- StringTokenizer st = new StringTokenizer(xmlName, "-");
- StringBuffer sb = new StringBuffer(st.nextToken());
- while (st.hasMoreTokens()) {
- sb.append(capitalize(st.nextToken()));
- }
- return sb.toString();
- }
-
- public static String toDefXmlTagName(XSObject xs) {
- String xmlName = xs.getName();
- if (xmlName.endsWith(TYPE_SUFFIX)) xmlName = xmlName.substring(0, xmlName.length() - 4);
- return xmlName;
- }
-
- public static String toDefXmlTagName(String tname) {
- String xmlName = tname;
- if (xmlName.endsWith(TYPE_SUFFIX)) xmlName = xmlName.substring(0, xmlName.length() - TYPE_SUFFIX.length());
- return xmlName;
- }
-
-
- public static boolean addToNameMap(Map<String, FieldDesc> fdMap, FieldDesc fd1, boolean merge) {
- boolean duplicates = false;
- FieldDesc fd2;
- if ((fd2 = fdMap.remove(fd1.name)) != null) {
- if (fd2.clType == FieldDesc.ATTR) {
- // attr <-> field
- fd2.name = fd1.name + "Attr";
- fdMap.put(fd2.name, fd2);
- } else if (merge) {
- fdMap.put(fd2.name, fd2);
- return false;
- } else {
- duplicates = true;
- fd2.name = fd1.name + "1";
- fd2.duplicateIndex = 1;
- fdMap.put(fd2.name, fd2);
- fd1.name = fd1.name + "2";
- fd1.duplicateIndex = 2;
- }
- } else if ((fd2 = fdMap.get(fd1.name + "1")) != null) {
- int id = 2;
- while (fdMap.containsKey(fd1.name + id)) id++;
- fd1.name = fd1.name + id;
- fd1.duplicateIndex = id;
- }
- fdMap.put(fd1.name, fd1);
- return duplicates;
- }
-
- public static String expandProperties(final String str, final Map<String, String> map) {
- if (str.indexOf("${") == -1) return str;
- int state = 0;
- final StringBuilder result = new StringBuilder();
- final StringBuilder variable = new StringBuilder();
- for (int i=0; i<str.length(); i++) {
- final char ch = str.charAt(i);
- switch (state) {
- case 0:
- if (ch == '$') state = 1;
- else result.append(ch);
- break;
- case 1:
- if (ch == '{') {
- state = 2;
- variable.setLength(0);
- }
- else {
- state = 0;
- result.append('$').append(ch);
- }
- break;
- case 2:
- if (ch == '}') {
- final String value = map.get(variable.toString());
- result.append(value == null? variable : value);
- state = 0;
- }
- else {
- variable.append(ch);
- }
- break;
- }
- }
- return result.toString();
- }
-}
-
diff --git a/xml/dom-impl/src/com/intellij/util/dom/generator/XSDModelLoader.java b/xml/dom-impl/src/com/intellij/util/dom/generator/XSDModelLoader.java
deleted file mode 100644
index c6cb362b7843..000000000000
--- a/xml/dom-impl/src/com/intellij/util/dom/generator/XSDModelLoader.java
+++ /dev/null
@@ -1,681 +0,0 @@
-/*
- * Copyright 2000-2010 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * XSD/DTD Model generator tool
- *
- * By Gregory Shrago
- * 2002 - 2006
- */
-package com.intellij.util.dom.generator;
-
-import org.apache.xerces.xs.*;
-import org.apache.xerces.impl.xs.XSComplexTypeDecl;
-import org.apache.xerces.impl.xs.XSParticleDecl;
-import org.apache.xerces.impl.xs.XSAttributeGroupDecl;
-import org.apache.xerces.impl.xs.XSElementDecl;
-import org.apache.xerces.impl.xs.util.XSObjectListImpl;
-import org.apache.xerces.impl.dv.XSSimpleType;
-import org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl;
-import org.apache.xerces.xni.parser.XMLEntityResolver;
-import org.w3c.dom.bootstrap.DOMImplementationRegistry;
-import org.w3c.dom.DOMConfiguration;
-import org.w3c.dom.DOMErrorHandler;
-import org.w3c.dom.DOMError;
-import org.w3c.dom.TypeInfo;
-
-import javax.xml.namespace.QName;
-import java.io.File;
-import java.util.*;
-
-/**
- * @author Gregory.Shrago
- * @author Konstantin Bulenkov
- */
-public class XSDModelLoader implements ModelLoader {
- private static final boolean TEXT_ELEMENTS_ARE_COMPLEX = false;
-
-
- private ModelDesc model;
-
- public void loadModel(ModelDesc model, Collection<File> files, XMLEntityResolver resolver) throws Exception {
- this.model = model;
- processSchemas(files, resolver);
- }
-
- public static boolean checkComplexType(XSTypeDefinition td) {
- if (td.getTypeCategory() != XSTypeDefinition.COMPLEX_TYPE) return false;
- XSComplexTypeDefinition ctd = (XSComplexTypeDefinition) td;
- if (ctd.getContentType() == XSComplexTypeDefinition.CONTENTTYPE_ELEMENT) {
- return true;
- }
- if ((td instanceof XSComplexTypeDecl) && ((XSComplexTypeDecl) td).getAbstract()) return true;
- if (TEXT_ELEMENTS_ARE_COMPLEX) return true;
- if (ctd.getAttributeUses() != null) {
- for (int i = 0; i < ctd.getAttributeUses().getLength(); i++) {
- XSSimpleTypeDefinition xsstd = ((XSAttributeUse) ctd.getAttributeUses().item(i)).getAttrDeclaration().getTypeDefinition();
- if ("ID".equals(xsstd.getName())) continue;
- return true;
- }
- }
- return false;
- }
-
- public static boolean checkEnumType(XSTypeDefinition td) {
- final XSSimpleTypeDefinition st;
- if (td.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) {
- XSComplexTypeDefinition ctd = (XSComplexTypeDefinition) td;
- if (ctd.getContentType() != XSComplexTypeDefinition.CONTENTTYPE_SIMPLE) return false;
- if (ctd.getAttributeUses() != null) {
- for (int i = 0; i < ctd.getAttributeUses().getLength(); i++) {
- XSSimpleTypeDefinition xsstd = ((XSAttributeUse) ctd.getAttributeUses().item(i)).getAttrDeclaration().getTypeDefinition();
- if ("ID".equals(xsstd.getName())) continue;
- return false;
- }
- }
- st = ctd.getSimpleType();
- } else if (td.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) {
- st = (XSSimpleTypeDefinition) td;
- } else {
- return false;
- }
- return st.getLexicalEnumeration() != null && st.getLexicalEnumeration().getLength() != 0;
- }
-
- private static boolean checkBooleanType(XSTypeDefinition td) {
- if (td.getTypeCategory() != XSTypeDefinition.SIMPLE_TYPE) return false;
- final XSSimpleTypeDefinition st = ((XSSimpleTypeDefinition) td);
- final XSObjectList facets = st.getFacets();
- for (int i = 0; i < facets.getLength(); i++) {
- final XSFacet facet = (XSFacet) facets.item(i);
- if (facet.getFacetKind() == XSSimpleTypeDefinition.FACET_LENGTH) {
- if ("0".equals(facet.getLexicalFacetValue())) {
- return true;
- }
- }
- }
- return false;
- }
-
-
- private XSModel loadSchema(File schemaFile, XMLEntityResolver resolver) throws Exception {
- // get DOM Implementation using DOM Registry
- System.setProperty(
- DOMImplementationRegistry.PROPERTY,
- "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
- DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
- XSImplementation impl = (XSImplementation) registry.getDOMImplementation("XS-Loader");
- XSLoader schemaLoader = impl.createXSLoader(null);
- DOMConfiguration config = schemaLoader.getConfig();
-
- // create Error Handler
- DOMErrorHandler errorHandler = new DOMErrorHandler() {
- public boolean handleError(DOMError domError) {
- Util.log("DOMError: " + domError.getMessage());
- Object relatedException = domError.getRelatedException();
- if (relatedException != null) {
- Util.log("DOMError: " + relatedException);
- if (relatedException instanceof Throwable) {
- ((Throwable) relatedException).printStackTrace(System.out);
- }
- }
- return false;
- }
- };
- // set error handler
- config.setParameter("error-handler", errorHandler);
- // set validation feature
- config.setParameter("validate", Boolean.TRUE);
- // parse document
- config.setParameter("error-handler", errorHandler);
- config.setParameter("http://apache.org/xml/properties/internal/entity-resolver", resolver);
-
- XSModel model = schemaLoader.loadURI(schemaFile.getAbsolutePath());
- if (model == null) return null;
- XSNamedMap components = model.getComponents(XSConstants.ELEMENT_DECLARATION);
- for (int i = 0; i < components.getLength(); i++) {
- XSObject obj = components.item(i);
- QName qname = new QName(obj.getNamespace(), obj.getName());
- String file = this.model.qname2FileMap.get(qname);
- this.model.qname2FileMap.put(qname, (file == null ? "" : file + ";") + schemaFile.getName());
- }
- components = model.getComponents(XSConstants.TYPE_DEFINITION);
- for (int i = 0; i < components.getLength(); i++) {
- XSObject obj = components.item(i);
- QName qname = new QName(obj.getNamespace(), obj.getName());
- String file = this.model.qname2FileMap.get(qname);
- this.model.qname2FileMap.put(qname, (file == null ? "" : file) + ":" + schemaFile.getName() + ":");
- }
- return model;
- }
-
- public void processSchemas(Collection<File> schemas, XMLEntityResolver resolver) throws Exception {
- Map<String, NamespaceDesc> nsdMap = model.nsdMap;
- Map<String, TypeDesc> jtMap = model.jtMap;
- final NamespaceDesc nsdDef = nsdMap.get("");
- final ArrayList<XSModel> models = new ArrayList<XSModel>();
- final HashMap<String, XSTypeDefinition> types = new HashMap<String, XSTypeDefinition>();
- for (File schemaFile : schemas) {
- String fileName = schemaFile.getPath();
- if (schemaFile.isDirectory() || !fileName.endsWith(".xsd")) {
- Util.log("skipping " + fileName);
- continue;
- }
- Util.log("loading " + fileName + "..");
-
- final XSModel model = loadSchema(schemaFile, resolver);
- if (model == null) continue;
-
- final StringList namespaceList = model.getNamespaces();
- for (int i = 0; i < namespaceList.getLength(); i++) {
- String ns = namespaceList.item(i);
- if (!nsdMap.containsKey(ns)) {
- Util.log("Adding default namespace desc for: " + ns);
- NamespaceDesc nsd = new NamespaceDesc(ns, nsdDef);
- nsdMap.put(ns, nsd);
- }
- }
- models.add(model);
- final XSNamedMap typeDefMap = model.getComponents(XSConstants.TYPE_DEFINITION);
- for (int i = 0; i < typeDefMap.getLength(); i++) {
- XSTypeDefinition o = (XSTypeDefinition) typeDefMap.item(i);
- NamespaceDesc nsd = nsdMap.get(o.getNamespace());
- if (nsd != null && nsd.skip) continue;
- final String key = o.getName() + "," + o.getNamespace();
- types.put(key, o);
- }
- final XSNamedMap elementDeclMap = model.getComponents(XSConstants.ELEMENT_DECLARATION);
- for (int i = 0; i < elementDeclMap.getLength(); i++) {
- XSElementDeclaration o = (XSElementDeclaration) elementDeclMap.item(i);
- if (o.getTypeDefinition().getAnonymous() && (o.getTypeDefinition() instanceof XSComplexTypeDefinition)) {
- //types.put(o.getName() + "," + o.getNamespace(), o);
- XSComplexTypeDefinition ctd = makeTypeFromAnonymous(o);
- NamespaceDesc nsd = nsdMap.get(o.getNamespace());
- if (nsd != null && nsd.skip) continue;
- final String key = ctd.getName() + "," + ctd.getNamespace();
- types.put(key, ctd);
- }
- }
- }
- Util.log(types.size() + " elements loaded, processing..");
- ArrayList<XSTypeDefinition> toProcess = new ArrayList<XSTypeDefinition>(types.values());
- ArrayList<XSComplexTypeDefinition> toAdd = new ArrayList<XSComplexTypeDefinition>();
- for (ListIterator<XSTypeDefinition> it = toProcess.listIterator(); it.hasNext();) {
- XSTypeDefinition td = it.next();
- Util.log("processing " + td.getName() + "," + td.getNamespace() + "..");
- if (checkComplexType(td)) {
- processType((XSComplexTypeDefinition) td, models, jtMap, nsdMap, toAdd);
- } else if (checkEnumType(td)) {
- processEnumType(td, jtMap, nsdMap);
- }
- if (toAdd.size() != 0) {
- for (XSComplexTypeDefinition o : toAdd) {
- final String key = o.getName() + "," + o.getNamespace();
- if (!types.containsKey(key)) {
- Util.log(" adding " + o.getName() + "," + o.getNamespace());
- types.put(key, o);
- it.add(o);
- it.previous();
- } else {
- Util.logwarn(key + " already exists");
- }
- }
- toAdd.clear();
- }
- }
- }
-
- private XSComplexTypeDefinition makeTypeFromAnonymous(XSObject o) {
- final XSComplexTypeDecl ctd = new XSComplexTypeDecl();
- if (o instanceof XSElementDeclaration && ((XSElementDeclaration) o).getTypeDefinition() instanceof XSComplexTypeDecl) {
- final XSComplexTypeDecl ctd1 = (XSComplexTypeDecl) ((XSElementDeclaration) o).getTypeDefinition();
- final XSObjectListImpl annotations = ctd1.getAnnotations() instanceof XSObjectListImpl ? (XSObjectListImpl) ctd1.getAnnotations() : new XSObjectListImpl();
- ctd.setValues(o.getName(), ctd1.getNamespace(), ctd1.getBaseType(), ctd1.getDerivationMethod(),
- ctd1.getFinal(), ctd1.getProhibitedSubstitutions(), ctd1.getContentType(),
- ctd1.getAbstract(), ctd1.getAttrGrp(), (XSSimpleType) ctd1.getSimpleType(),
- (XSParticleDecl) ctd1.getParticle(), annotations);
- ctd.setName(o.getName() + Util.ANONYMOUS_ELEM_TYPE_SUFFIX);
- } else if (o instanceof XSAttributeDeclaration) {
- final XSSimpleTypeDecl ctd1 = (XSSimpleTypeDecl) ((XSAttributeDeclaration) o).getTypeDefinition();
- final XSObjectListImpl annotations = ctd1.getAnnotations() instanceof XSObjectListImpl ? (XSObjectListImpl) ctd1.getAnnotations() : new XSObjectListImpl();
- ctd.setValues(o.getName(), ctd1.getNamespace(), ctd1.getBaseType(), XSConstants.DERIVATION_RESTRICTION,
- ctd1.getFinal(), (short) 0, XSComplexTypeDefinition.CONTENTTYPE_SIMPLE,
- false, new XSAttributeGroupDecl(), ctd1,
- null, annotations);
- ctd.setName(o.getName() + Util.ANONYMOUS_ATTR_TYPE_SUFFIX);
- }
-
- model.qname2FileMap.put(new QName(ctd.getNamespace(), ctd.getName()), model.qname2FileMap.get(new QName(o.getNamespace(), o.getName())));
- return ctd;
- }
-
- public void processEnumType(XSTypeDefinition def, Map<String, TypeDesc> jtMap, Map<String, NamespaceDesc> nsdMap) throws Exception {
- boolean complexType = def instanceof XSComplexTypeDefinition;
- if (!nsdMap.containsKey(def.getNamespace())) {
- Util.log("Namespace desc not found for: " + def);
- }
- final String typeName = toJavaTypeName(def, nsdMap);
- final TypeDesc td = new TypeDesc(def.getName(), def.getNamespace(), typeName, TypeDesc.TypeEnum.ENUM);
- final XSComplexTypeDefinition ct = complexType ? (XSComplexTypeDefinition) def : null;
- final XSSimpleTypeDefinition st = (XSSimpleTypeDefinition) (complexType ? ((XSComplexTypeDefinition) def).getSimpleType() : def);
- for (int i = 0; i < st.getLexicalEnumeration().getLength(); i++) {
- final String s = st.getLexicalEnumeration().item(i);
- td.fdMap.put(s, new FieldDesc(Util.computeEnumConstantName(s, td.name), s));
- }
-
- final XSObjectList anns = complexType ? ct.getAnnotations() : st.getAnnotations();
-
- td.documentation = parseAnnotationString("Enumeration " + def.getNamespace() + ":" + def.getName() + " documentation", anns != null && anns.getLength() > 0 ? ((XSAnnotation) anns.item(0)).getAnnotationString() : null);
- jtMap.put(model.toJavaQualifiedTypeName(def, nsdMap, true), td);
- }
-
- public void processType(XSComplexTypeDefinition def, List<XSModel> models, Map<String, TypeDesc> jtMap, Map<String, NamespaceDesc> nsdMap, ArrayList<XSComplexTypeDefinition> toAdd) throws Exception {
- if (!nsdMap.containsKey(def.getNamespace())) {
- Util.log("Namespace desc not found for: " + def);
- }
- String typeName = toJavaTypeName(def, nsdMap);
- TypeDesc td = jtMap.get(model.toJavaQualifiedTypeName(def, nsdMap, false));
- if (td != null) {
- if (td.fdMap.size() == 0) {
- // Util.log("Reusing forward decl: "+typeName);
- } else {
- Util.logerr("merging: type names collision: " + typeName);
- }
- } else {
- td = new TypeDesc(def.getName(), def.getNamespace(), typeName, TypeDesc.TypeEnum.CLASS);
- }
- XSObjectList anns = def.getAnnotations();
- td.documentation = parseAnnotationString("Type " + def.getNamespace() + ":" + def.getName() + " documentation",
- anns != null && anns.getLength() > 0 ? ((XSAnnotation) anns.item(0)).getAnnotationString() : null);
- TypeDesc tdBase = null;
- if (checkComplexType(def.getBaseType())) {
- XSComplexTypeDefinition base = (XSComplexTypeDefinition) def.getBaseType();
- String typeNameBase = toJavaTypeName(base, nsdMap);
- if ((tdBase = jtMap.get(model.toJavaQualifiedTypeName(base, nsdMap, false))) == null) {
- // logwarn("forward decl: "+et);
- tdBase = new TypeDesc(base.getName(), base.getNamespace(), typeNameBase, TypeDesc.TypeEnum.CLASS);
- jtMap.put(model.toJavaQualifiedTypeName(base, nsdMap, false), tdBase);
- }
- }
- if (def.getSimpleType() != null || def.getContentType() == XSComplexTypeDefinition.CONTENTTYPE_MIXED) {
- FieldDesc fd = new FieldDesc(FieldDesc.SIMPLE, "value", "String", null, "null", true);
- fd.realIndex = td.fdMap.size();
- td.fdMap.put(fd.name, fd);
- }
- XSObjectList attrs = def.getAttributeUses();
- for (int i = 0; i < attrs.getLength(); i++) {
- XSAttributeUse au = (XSAttributeUse) attrs.item(i);
- XSAttributeDeclaration ad = au.getAttrDeclaration();
- XSSimpleTypeDefinition atd = ad.getTypeDefinition();
- XSAnnotation ann = ad.getAnnotation();
- String documentation = parseAnnotationString("Attribute " + ad.getNamespace() + ":" + ad.getName() + " documentation", ann != null ? ann.getAnnotationString() : null);
- // skip "ID" and "FIXED"
- if ("ID".equals(atd.getName())) continue;
- // "language", "dewey-versionType", "boolean"
- if (ad.getConstraintType() == XSConstants.VC_FIXED) continue;
- FieldDesc fd1 = new FieldDesc(FieldDesc.ATTR, Util.toJavaFieldName(ad.getName()), "String", null, "null", au.getRequired());
- fd1.tagName = ad.getName();
- fd1.documentation = documentation;
- fd1.realIndex = td.fdMap.size();
- td.duplicates = Util.addToNameMap(td.fdMap, fd1, false) || td.duplicates;
- if (checkEnumType(ad.getTypeDefinition())) {
- XSTypeDefinition etRoot = ad.getTypeDefinition();
- if (etRoot.getAnonymous()) {
- etRoot = makeTypeFromAnonymous(ad);
- if (toAdd != null) toAdd.add((XSComplexTypeDefinition) etRoot);
- }
- fd1.type = toJavaTypeName(etRoot, nsdMap);
- fd1.contentQualifiedName = model.toJavaQualifiedTypeName(etRoot, nsdMap, true);
- // forward decl
- if (jtMap.get(fd1.contentQualifiedName) == null) {
- // logwarn("forward decl: "+et);
- TypeDesc ftd = new TypeDesc(etRoot.getName(), etRoot.getNamespace(), fd1.type, TypeDesc.TypeEnum.ENUM);
- jtMap.put(fd1.contentQualifiedName, ftd);
-// // anonymous (simple type) enum
-// if (ad.getTypeDefinition().getAnonymous()) {
-// processEnumType(ad.getTypeDefinition(), jtMap, nsdMap);
-// }
- }
- } else {
- fd1.simpleTypesString = getSimpleTypesString(ad.getTypeDefinition());
- }
- }
- LinkedList<PEntry> plist = new LinkedList<PEntry>();
- if (def.getParticle() != null) {
- plist.add(new PEntry(def.getParticle(), false));
- }
- processParticles(def, plist, nsdMap, jtMap, td, models, toAdd, tdBase);
- jtMap.put(model.toJavaQualifiedTypeName(def, nsdMap, false), td);
- if (td.fdMap.size() == 1 && def.getSimpleType() != null) {
- // calc type hierarchy for simple content
- FieldDesc fd = td.fdMap.get("value");
- fd.simpleTypesString = getSimpleTypesString(def);
- }
- }
-
- private static String getSimpleTypesString(XSTypeDefinition et) {
- StringBuffer typesHierarchy = new StringBuffer();
- while (et != null && !"anySimpleType".equals(et.getName()) && !"anyType".equals(et.getName()) && et.getNamespace() != null) {
- typesHierarchy.append(et.getNamespace().substring(et.getNamespace().lastIndexOf("/") + 1)).append(":").append(et.getName()).append(";");
- if (et instanceof XSSimpleType) {
- XSSimpleType simpleType = (XSSimpleType) et;
- if (simpleType.getVariety() == XSSimpleTypeDefinition.VARIETY_LIST
- || simpleType.getVariety() == XSSimpleTypeDefinition.VARIETY_UNION) {
- XSObjectList list = simpleType.getMemberTypes();
- if (list.getLength() > 0) {
- typesHierarchy.append("{");
- for (int i = 0; i < list.getLength(); i++) {
- typesHierarchy.append(getSimpleTypesString((XSTypeDefinition) list.item(i)));
- }
- typesHierarchy.append("}");
- }
- }
- }
- et = et.getBaseType();
- }
- return typesHierarchy.toString();
- }
-
- private TypeDesc processGroup(XSModelGroup modelGroup, List<XSModel> models, Map<String, TypeDesc> jtMap, Map<String, NamespaceDesc> nsdMap) {
- XSModelGroupDefinition def = null;
- for (XSModel xsModel : models) {
- XSNamedMap map = xsModel.getComponents(XSConstants.MODEL_GROUP_DEFINITION);
- for (int i = 0; i < map.getLength(); i++) {
- XSModelGroupDefinition mg = (XSModelGroupDefinition) map.item(i);
- final XSModelGroup xsModelGroup = mg.getModelGroup();
- if (xsModelGroup == modelGroup || xsModelGroup.toString().equals(modelGroup.toString())) {
- def = mg;
- break;
- }
- }
- }
- if (def == null) return null;
- if (!nsdMap.containsKey(def.getNamespace())) {
- Util.log("Namespace desc not found for: " + def);
- }
- String typeName = toJavaTypeName(def, nsdMap);
- final String typeQName = model.toJavaQualifiedTypeName(def, nsdMap, false);
- TypeDesc td = jtMap.get(typeQName);
- if (td != null) {
- if (td.type == TypeDesc.TypeEnum.GROUP_INTERFACE) {
- return td;
- } else {
- Util.logerr("type-group conflict: " + typeName);
- return null;
- }
- } else {
- td = new TypeDesc(def.getName(), def.getNamespace(), typeName, TypeDesc.TypeEnum.GROUP_INTERFACE);
- }
-
- XSAnnotation ann = def.getAnnotation();
- td.documentation = parseAnnotationString("Type " + def.getNamespace() + ":" + def.getName() + " documentation",
- ann == null ? null : ann.getAnnotationString());
- td.type = TypeDesc.TypeEnum.GROUP_INTERFACE;
- LinkedList<PEntry> plist = new LinkedList<PEntry>();
- for (int i = 0; i < def.getModelGroup().getParticles().getLength(); i++) {
- XSParticle p = (XSParticle) def.getModelGroup().getParticles().item(i);
- plist.add(new PEntry(p, false));
- }
- processParticles(def, plist, nsdMap, jtMap, td, models, null, null);
- jtMap.put(typeQName, td);
- return td;
- }
-
- private void processParticles(XSObject def, LinkedList<PEntry> plist, Map<String, NamespaceDesc> nsdMap, Map<String, TypeDesc> jtMap, TypeDesc td, List<XSModel> models, ArrayList<XSComplexTypeDefinition> toAdd, TypeDesc baseClass) {
- final boolean globalMerge = jtMap.containsKey(model.toJavaQualifiedTypeName(def, nsdMap, td.type == TypeDesc.TypeEnum.ENUM));
- final HashMap<XSParticle, String> globalChoice = new HashMap<XSParticle, String>();
- final ArrayList<XSObjectList> choiceList = new ArrayList<XSObjectList>();
- final ArrayList<TypeDesc> supers = new ArrayList<TypeDesc>();
- if (baseClass != null) {
- supers.add(baseClass);
- }
- while (!plist.isEmpty()) {
- final PEntry pentry = plist.removeFirst();
- final XSParticle p = pentry.p;
- if (p.getTerm() instanceof XSElementDecl) {
- final XSElementDecl el = (XSElementDecl) p.getTerm();
- if (el.getConstraintType() == XSConstants.VC_FIXED) continue;
- XSTypeDefinition etRoot = el.getTypeDefinition();
- XSTypeDefinition et = etRoot;
- XSAnnotation ann = el.getAnnotation();
- String documentation = parseAnnotationString("Element " + el.getNamespace() + ":" + el.getName() + " documentation", ann != null ? ann.getAnnotationString() : null);
- final FieldDesc fd1 = new FieldDesc(FieldDesc.STR, Util.toJavaFieldName(el.getName()), et.getName(), null, "null", !pentry.many && p.getMinOccurs() > 0);
- fd1.documentation = documentation;
- fd1.tagName = el.getName();
- while (et.getBaseType() != null && !"anySimpleType".equals(et.getBaseType().getName()) && !"anyType".equals(et.getBaseType().getName())) {
- et = et.getBaseType();
- }
- if (checkEnumType(etRoot)) {
- if (etRoot.getAnonymous()) {
- etRoot = makeTypeFromAnonymous(el);
- if (toAdd != null) toAdd.add((XSComplexTypeDefinition) etRoot);
- }
- fd1.type = toJavaTypeName(etRoot, nsdMap);
- fd1.clType = FieldDesc.OBJ;
- fd1.contentQualifiedName = model.toJavaQualifiedTypeName(etRoot, nsdMap, true);
- // forward decl
- if (!jtMap.containsKey(fd1.contentQualifiedName)) {
- // logwarn("forward decl: "+et);
- TypeDesc ftd = new TypeDesc(etRoot.getName(), etRoot.getNamespace(), fd1.type, TypeDesc.TypeEnum.ENUM);
- jtMap.put(fd1.contentQualifiedName, ftd);
- }
- } else if (checkComplexType(etRoot)) {
- if (etRoot.getAnonymous()) {
- etRoot = makeTypeFromAnonymous(el);
- if (toAdd != null) toAdd.add((XSComplexTypeDefinition) etRoot);
- }
- fd1.type = toJavaTypeName(etRoot, nsdMap);
- fd1.clType = FieldDesc.OBJ;
- fd1.contentQualifiedName = model.toJavaQualifiedTypeName(etRoot, nsdMap, false);
- // forward decl
- if (jtMap.get(fd1.contentQualifiedName) == null) {
- //logwarn("forward decl: "+etRoot);
- jtMap.put(fd1.contentQualifiedName, new TypeDesc(etRoot.getName(), etRoot.getNamespace(), fd1.type, TypeDesc.TypeEnum.CLASS));
- }
- } else if (checkBooleanType(etRoot)) {
- fd1.type = "boolean";
- fd1.clType = FieldDesc.BOOL;
- } else {
- if (etRoot instanceof XSComplexTypeDefinition) {
- final XSComplexTypeDefinition ct = (XSComplexTypeDefinition) etRoot;
- // XXX xerces2.7.1 wierd annotation inheritance bug fix
- //ann = (XSAnnotation) (ct.getAnnotations()!=null && ct.getAnnotations().getLength()>0?ct.getAnnotations().item(0):null);
- ann = (XSAnnotation) (ct.getAnnotations() != null && ct.getAnnotations().getLength() > 0 ? ct.getAnnotations().item(ct.getAnnotations().getLength() - 1) : null);
- documentation = parseAnnotationString("Type " + ct.getNamespace() + ":" + ct.getName() + " documentation", ann != null ? ann.getAnnotationString() : null);
- if (documentation != null) {
- fd1.documentation = fd1.documentation != null ? fd1.documentation + "\n" + documentation : documentation;
- }
- }
- fd1.simpleTypesString = getSimpleTypesString(etRoot);
-
- // "fully-qualified-classType", "jndi-nameType", "transaction-typeType"
- // "java-identifierType", "pathType"
- fd1.type = et.getName();
- if (fd1.type == null) {
- fd1.type = "String";
- fd1.def = "null";
- fd1.clType = FieldDesc.STR;
-// fd1.type = "boolean";
-// fd1.def = "false";
-// fd1.clType = FieldDesc.BOOL;
- } else if (fd1.type.equals("string") || fd1.type.equals("anyURI")) {
- fd1.type = "String";
- } else if (fd1.type.equals("boolean")) {
- fd1.type = "String";
- } else if (fd1.type.equals("emptyType")) {
- fd1.type = "boolean";
- fd1.def = "false";
- fd1.clType = FieldDesc.BOOL;
- } else if (fd1.type.equals("decimal")) {
- fd1.type = "String";
- fd1.def = "\"0.0\"";
- } else if (fd1.type.equals("QName")) {
- fd1.type = "String";
- } else if (fd1.type.equals("extensibleType")) {
- fd1.type = "Object";
- } else {
- if (et.getBaseType() != null &&
- ("anySimpleType".equals(et.getBaseType().getName())
- || "anyType".equals(et.getBaseType().getName()))) {
- fd1.type = "String";
- fd1.def = "null";
- fd1.clType = FieldDesc.STR;
- } else {
- fd1.type = "boolean";
- fd1.def = "false";
- fd1.clType = FieldDesc.BOOL;
- }
- Util.logwarn("using '" + fd1.type + "' for unknown base type: " + et.getName() + " for " + el);
- }
- }
- if ((pentry.many || p.getMaxOccursUnbounded() || p.getMaxOccurs() > 1) && fd1.clType != FieldDesc.BOOL) {
- fd1.elementType = fd1.type;
- fd1.elementName = fd1.name;
- fd1.type = "List<" + fd1.elementType + ">";
- fd1.name = Util.pluralize(fd1.name);
- fd1.def = "new ArrayList(0)";
- fd1.clType = -fd1.clType;
- fd1.comment = "array of " + fd1.elementType;
- }
- fd1.realIndex = td.fdMap.size();
- boolean merge = globalMerge || globalChoice.containsKey(p) && globalChoice.values().contains(fd1.name);
- td.duplicates = Util.addToNameMap(td.fdMap, fd1, merge) || td.duplicates;
- globalChoice.put(p, fd1.name);
- } else if (p.getTerm() instanceof XSModelGroup) {
- boolean addToGlobalChoice = false;
- boolean many = p.getMaxOccursUnbounded() || p.getMaxOccurs() > 1;
- XSObjectList l = ((XSModelGroup) p.getTerm()).getParticles();
- if (!many) {
- if (((XSModelGroup) p.getTerm()).getCompositor() == XSModelGroup.COMPOSITOR_CHOICE) {
- addToGlobalChoice = true;
- choiceList.add(l);
- } else {
- // generate group interface???
- XSModelGroup groupDef = (XSModelGroup) p.getTerm();
- TypeDesc gtd = processGroup(groupDef, models, jtMap, nsdMap);
- if (gtd != null) supers.add(gtd);
- }
- }
- if (globalChoice.containsKey(p)) {
- addToGlobalChoice = true;
- }
- for (int i = 0; i < l.getLength(); i++) {
- final PEntry o = new PEntry((XSParticle) l.item(i), many);
- plist.add(o);
- if (addToGlobalChoice && !globalChoice.containsKey(o.p)) {
- globalChoice.put(o.p, null);
- }
- }
- }
- }
- int i = 0;
- for (Iterator<FieldDesc> it = td.fdMap.values().iterator(); it.hasNext(); i++) {
- FieldDesc fd = it.next();
- fd.idx = i;
- }
- for (XSObjectList l : choiceList) {
- final ArrayList<XSParticle> clist = new ArrayList<XSParticle>();
- final LinkedList<XSParticle> elist = new LinkedList<XSParticle>();
- for (i = 0; i < l.getLength(); i++) {
- elist.add((XSParticle) l.item(i));
- }
- while (!elist.isEmpty()) {
- final XSParticle p = elist.removeFirst();
- if (p.getTerm() instanceof XSModelGroup) {
- XSObjectList l2 = ((XSModelGroup) p.getTerm()).getParticles();
- for (int i2 = 0; i2 < l2.getLength(); i2++) {
- elist.addFirst((XSParticle) l2.item(i2));
- }
- } else if (p.getTerm() instanceof XSElementDecl) {
- clist.add(p);
- }
- }
- boolean choiceOpt = true;
- FieldDesc[] choice = new FieldDesc[clist.size()];
- for (i = 0; i < choice.length; i++) {
- XSParticle p = clist.get(i);
- XSElementDecl el = (XSElementDecl) p.getTerm();
- String s = Util.toJavaFieldName(el.getName());
- if (p.getMaxOccursUnbounded() || p.getMaxOccurs() > 1) {
- s = Util.pluralize(s);
- }
- FieldDesc fd = td.fdMap.get(s);
- if (fd == null) {
- fd = td.fdMap.get(Util.pluralize(s));
- if (fd == null) {
- Util.logerr("uknown choice element: " + s);
- }
- }
-
- if (fd != null) {
- choice[i] = fd;
- choice[i].choice = choice;
- if (fd.required) choiceOpt = false;
- }
- }
- for (i = 0; i < choice.length; i++) {
- if (choice[i] != null) {
- choice[i].choiceOpt = choiceOpt;
- }
- }
- }
- td.supers = supers.toArray(new TypeDesc[supers.size()]);
- }
- public static String parseAnnotationString(String title, String str) {
- if (str == null) return null;
- int idx = str.indexOf(":documentation");
- if (idx == -1) idx = str.indexOf("<documentation");
- if (idx == -1) return null;
- idx = str.indexOf(">", idx + 1);
- if (idx == -1) return null;
- int idx2 = str.indexOf(":documentation", idx + 1);
- if (idx2 == -1) idx2 = str.indexOf("</documentation", idx + 1);
- idx2 = str.lastIndexOf("<", idx2 + 1);
- str = str.substring(idx + 1, idx2).trim();
-
- idx = str.indexOf("<![CDATA[");
- if (idx > -1) {
- idx = str.indexOf("[", idx + 3);
- idx2 = str.indexOf("]]>", idx + 1);
- str = str.substring(idx + 1, idx2);
- }
- return "<pre>\n<h3>" + title + "</h3>\n" + str + "\n</pre>";
- }
-
- public String toJavaTypeName(XSObject xs, Map<String, NamespaceDesc> nsdMap) {
- String name = xs.getName();
- if (name == null) {
- if (xs instanceof TypeInfo) {
- name = ((TypeInfo) xs).getTypeName();
- if (name != null && name.startsWith("#")) {
- name = name.substring(1);
- }
- }
- }
- return model.toJavaTypeName(name, xs.getNamespace());
- }
-
- public static class PEntry {
- public PEntry(XSParticle p, boolean many) {
- this.p = p;
- this.many = many;
- }
-
- XSParticle p;
- boolean many;
- }
-
-}
diff --git a/xml/dom-impl/src/com/intellij/util/xml/EnumConverter.java b/xml/dom-impl/src/com/intellij/util/xml/EnumConverter.java
index fd24a9e4afef..8dc15edb48e2 100644
--- a/xml/dom-impl/src/com/intellij/util/xml/EnumConverter.java
+++ b/xml/dom-impl/src/com/intellij/util/xml/EnumConverter.java
@@ -1,10 +1,10 @@
package com.intellij.util.xml;
+import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.containers.ConcurrentFactoryMap;
import com.intellij.xml.util.XmlUtil;
-import com.intellij.codeInsight.CodeInsightBundle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java
index 663fb7f40cdc..f72dcbf4ab03 100644
--- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java
+++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java
@@ -217,7 +217,8 @@ public abstract class DomInvocationHandler<T extends AbstractDomChildDescription
assert existing != null : existing + "\n---------\n" + tag.getParent().getText() + "\n-----------\n" + tag.getText();
assert getProxy().equals(existing) : existing + "\n---------\n" + tag.getParent().getText() + "\n-----------\n" + tag.getText() + "\n----\n" + this + " != " +
DomManagerImpl.getDomInvocationHandler(existing);
- final SmartPsiElementPointer<XmlTag> pointer = SmartPointerManager.getInstance(myManager.getProject()).createLazyPointer(tag);
+ final SmartPsiElementPointer<XmlTag> pointer =
+ SmartPointerManager.getInstance(myManager.getProject()).createSmartPsiElementPointer(tag);
return myManager.createStableValue(new StableCopyFactory<T>(pointer, myType, getClass()));
}
return (T)createPathStableCopy();
diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/FileDescriptionCachedValueProvider.java b/xml/dom-impl/src/com/intellij/util/xml/impl/FileDescriptionCachedValueProvider.java
index e3bccbd9886e..dcb04f3f6b48 100644
--- a/xml/dom-impl/src/com/intellij/util/xml/impl/FileDescriptionCachedValueProvider.java
+++ b/xml/dom-impl/src/com/intellij/util/xml/impl/FileDescriptionCachedValueProvider.java
@@ -20,6 +20,7 @@ import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileWithId;
+import com.intellij.psi.impl.PsiFileEx;
import com.intellij.psi.stubs.ObjectStubTree;
import com.intellij.psi.stubs.StubTreeLoader;
import com.intellij.psi.xml.XmlFile;
@@ -114,7 +115,7 @@ class FileDescriptionCachedValueProvider<T extends DomElement> implements SemEle
VirtualFile file = myXmlFile.getVirtualFile();
FileStub stub = null;
- if (description.hasStubs() && file instanceof VirtualFileWithId) {
+ if (description.hasStubs() && file instanceof VirtualFileWithId && !isFileParsed()) {
ApplicationManager.getApplication().assertReadAccessAllowed();
if (!XmlUtil.isStubBuilding(myXmlFile)) {
ObjectStubTree stubTree = StubTreeLoader.getInstance().readOrBuild(myXmlFile.getProject(), file, myXmlFile);
@@ -135,6 +136,10 @@ class FileDescriptionCachedValueProvider<T extends DomElement> implements SemEle
return result;
}
+ private boolean isFileParsed() {
+ return myXmlFile instanceof PsiFileEx && ((PsiFileEx)myXmlFile).isContentsLoaded();
+ }
+
@Nullable
private DomFileDescription<T> findFileDescription(final XmlFileHeader rootTagName, @Nullable StringBuilder sb) {
final DomFileDescription<T> mockDescription = myXmlFile.getUserData(DomManagerImpl.MOCK_DESCRIPTION);
diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/ErrorableTableCellRenderer.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/ErrorableTableCellRenderer.java
index 7ce604e475db..59b40c101b58 100644
--- a/xml/dom-openapi/src/com/intellij/util/xml/ui/ErrorableTableCellRenderer.java
+++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/ErrorableTableCellRenderer.java
@@ -80,7 +80,7 @@ public class ErrorableTableCellRenderer<T extends DomElement> extends DefaultTab
}
else if (warningProblems.size() > 0) {
component.setBackground(BaseControl.WARNING_BACKGROUND);
- if(isSelected) component.setForeground(JBColor.foreground);
+ if(isSelected) component.setForeground(JBColor.foreground());
}
final List<DomElementProblemDescriptor> errorDescriptors =
diff --git a/xml/impl/resources/inspectionDescriptions/XmlInvalidId.html b/xml/impl/resources/inspectionDescriptions/XmlInvalidId.html
new file mode 100644
index 000000000000..332e802540df
--- /dev/null
+++ b/xml/impl/resources/inspectionDescriptions/XmlInvalidId.html
@@ -0,0 +1,6 @@
+<html>
+<body>
+<font face="verdana" size="-1">This inspection checks for unresolved "id" attributes in XML.
+</font>
+</body>
+</html> \ No newline at end of file
diff --git a/xml/impl/resources/liveTemplates/zen_html.xml b/xml/impl/resources/liveTemplates/zen_html.xml
index 7f537b53fb32..c7aaa6094a1c 100644
--- a/xml/impl/resources/liveTemplates/zen_html.xml
+++ b/xml/impl/resources/liveTemplates/zen_html.xml
@@ -608,7 +608,7 @@
<option name="HTML_TEXT" value="true"/>
</context>
</template>
- <template description="&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;....css&quot; media=&quot;all&quot;&gt;" name="link:css" toReformat="true" toShortenFQNames="true" value="&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;$END$.css&quot; media=&quot;all&quot;/&gt;">
+ <template description="&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;....css&quot; /&gt;" name="link:css" toReformat="true" toShortenFQNames="true" value="&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;$END$.css&quot; /&gt;">
<context>
<option name="HTML_TEXT" value="true"/>
</context>
@@ -655,6 +655,21 @@
<option name="HTML_TEXT" value="true"/>
</context>
</template>
+ <template description="&lt;button type=&quot;button&quot;&gt;...&lt;/button&gt;" name="btn:b" toReformat="true" toShortenFQNames="true" value="&lt;button type=&quot;button&quot;&gt;$END$&lt;/button&gt;">
+ <context>
+ <option name="HTML_TEXT" value="true"/>
+ </context>
+ </template>
+ <template description="&lt;button type=&quot;reset&quot;&gt;...&lt;/button&gt;" name="btn:r" toReformat="true" toShortenFQNames="true" value="&lt;button type=&quot;reset&quot;&gt;$END$&lt;/button&gt;">
+ <context>
+ <option name="HTML_TEXT" value="true"/>
+ </context>
+ </template>
+ <template description="&lt;button type=&quot;submit&quot;&gt;...&lt;/button&gt;" name="btn:s" toReformat="true" toShortenFQNames="true" value="&lt;button type=&quot;submit&quot;&gt;$END$&lt;/button&gt;">
+ <context>
+ <option name="HTML_TEXT" value="true"/>
+ </context>
+ </template>
<template description="&lt;input type=&quot;url&quot; name=&quot;...&quot; id=&quot;...&quot;/&gt;" name="input:url" toReformat="true" toShortenFQNames="true" value="&lt;input type=&quot;url&quot; name=&quot;$VAR0$&quot; id=&quot;$VAR1$&quot;/&gt;">
<variable alwaysStopAt="true" defaultValue="&quot;&quot;" expression="" name="VAR0"/>
<variable alwaysStopAt="true" defaultValue="&quot;&quot;" expression="" name="VAR1"/>
diff --git a/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.form b/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.form
index 62127bcf42e3..e427db7d292c 100644
--- a/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.form
+++ b/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.form
@@ -21,8 +21,8 @@
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="1" use-parent-layout="false"/>
</constraints>
<properties>
- <labelFor value="ce319"/>
- <text value="Expand abbreviation with"/>
+ <labelFor value="59f5a"/>
+ <text resource-bundle="messages/XmlBundle" key="emmet.expand.abbreviation.with"/>
</properties>
</component>
<component id="59f5a" class="javax.swing.JComboBox" binding="myEmmetExpandShortcutCombo">
@@ -54,7 +54,7 @@
</component>
</children>
</grid>
- <grid id="bd64d" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+ <grid id="bd64d" layout-manager="GridLayoutManager" row-count="3" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
@@ -67,7 +67,7 @@
<children>
<component id="65354" class="com.intellij.ui.components.JBCheckBox" binding="myAutoInsertCssVendorJBCheckBox" default-binding="true">
<constraints>
- <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
+ <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/XmlBundle" key="emmet.auto.insert.vendor.prefixes"/>
@@ -76,12 +76,20 @@
<grid id="612b" binding="myPrefixesPanel" custom-create="true" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
- <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+ <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
+ <component id="b1849" class="com.intellij.ui.components.JBCheckBox" binding="myEnabledFuzzySearchJBCheckBox">
+ <constraints>
+ <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
+ </constraints>
+ <properties>
+ <text resource-bundle="messages/XmlBundle" key="emmet.fuzzy.search"/>
+ </properties>
+ </component>
</children>
</grid>
</children>
diff --git a/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.java b/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.java
index a8df5388e5c7..a702df6fde61 100644
--- a/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.java
+++ b/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.java
@@ -40,6 +40,7 @@ public class EmmetConfigurable implements SearchableConfigurable, Disposable, Co
private JComboBox myEmmetExpandShortcutCombo;
private JBCheckBox myEnableBEMFilterJBCheckBox;
private JBCheckBox myAutoInsertCssVendorJBCheckBox;
+ private JBCheckBox myEnabledFuzzySearchJBCheckBox;
private JPanel myPanel;
private JPanel myPrefixesPanel;
@@ -59,6 +60,7 @@ public class EmmetConfigurable implements SearchableConfigurable, Disposable, Co
myAutoInsertCssVendorJBCheckBox.setEnabled(selected);
myCssEditPrefixesListPanel.setEnabled(selected && myAutoInsertCssVendorJBCheckBox.isSelected());
myEnableBEMFilterJBCheckBox.setEnabled(selected);
+ myEnabledFuzzySearchJBCheckBox.setEnabled(selected);
}
});
@@ -125,6 +127,7 @@ public class EmmetConfigurable implements SearchableConfigurable, Disposable, Co
return emmetOptions.isEmmetEnabled() != myEnableEmmetJBCheckBox.isSelected() ||
emmetOptions.isBemFilterEnabledByDefault() != myEnableBEMFilterJBCheckBox.isSelected() ||
emmetOptions.isAutoInsertCssPrefixedEnabled() != myAutoInsertCssVendorJBCheckBox.isSelected() ||
+ emmetOptions.isFuzzySearchEnabled() != myEnabledFuzzySearchJBCheckBox.isSelected() ||
!emmetOptions.getAllPrefixInfo().equals(myCssEditPrefixesListPanel.getState()) ||
emmetOptions.getEmmetExpandShortcut() != getSelectedEmmetExpandShortcut();
}
@@ -137,6 +140,7 @@ public class EmmetConfigurable implements SearchableConfigurable, Disposable, Co
emmetOptions.setEnableBemFilterByDefault(myEnableBEMFilterJBCheckBox.isSelected());
emmetOptions.setEmmetExpandShortcut(getSelectedEmmetExpandShortcut());
emmetOptions.setAutoInsertCssPrefixedEnabled(myAutoInsertCssVendorJBCheckBox.isSelected());
+ emmetOptions.setFuzzySearchEnabled(myEnabledFuzzySearchJBCheckBox.isSelected());
emmetOptions.setPrefixInfo(myCssEditPrefixesListPanel.getState());
}
@@ -149,6 +153,8 @@ public class EmmetConfigurable implements SearchableConfigurable, Disposable, Co
myEmmetExpandShortcutCombo.setEnabled(emmetOptions.isEmmetEnabled());
myAutoInsertCssVendorJBCheckBox.setEnabled(emmetOptions.isEmmetEnabled());
myAutoInsertCssVendorJBCheckBox.setSelected(emmetOptions.isAutoInsertCssPrefixedEnabled());
+ myEnabledFuzzySearchJBCheckBox.setEnabled(emmetOptions.isEmmetEnabled());
+ myEnabledFuzzySearchJBCheckBox.setSelected(emmetOptions.isFuzzySearchEnabled());
//myInsertFallbackGradientColorJBCheckBox.setEnabled(emmetOptions.isEmmetEnabled());
//myInsertFallbackGradientColorJBCheckBox.setSelected(emmetOptions.isInsertFallbackGradientColorEnabled());
diff --git a/xml/impl/src/com/intellij/application/options/emmet/EmmetOptions.java b/xml/impl/src/com/intellij/application/options/emmet/EmmetOptions.java
index 70ddaa453aae..dd005841293c 100644
--- a/xml/impl/src/com/intellij/application/options/emmet/EmmetOptions.java
+++ b/xml/impl/src/com/intellij/application/options/emmet/EmmetOptions.java
@@ -51,6 +51,7 @@ public class EmmetOptions implements PersistentStateComponent<EmmetOptions>, Exp
private boolean myEnableBemFilterByDefault = false;
private boolean myEmmetEnabled = WebEditorOptions.getInstance().isZenCodingEnabled();
private int myEmmetExpandShortcut = WebEditorOptions.getInstance().getZenCodingExpandShortcut();
+ private boolean myFuzzySearchEnabled = true;
private boolean myAutoInsertCssPrefixedEnabled = true;
@Nullable
private Map<String, Integer> prefixes = null;
@@ -106,6 +107,14 @@ public class EmmetOptions implements PersistentStateComponent<EmmetOptions>, Exp
myAutoInsertCssPrefixedEnabled = autoInsertCssPrefixedEnabled;
}
+ public void setFuzzySearchEnabled(boolean fuzzySearchEnabled) {
+ myFuzzySearchEnabled = fuzzySearchEnabled;
+ }
+
+ public boolean isFuzzySearchEnabled() {
+ return myFuzzySearchEnabled;
+ }
+
@NotNull
@Override
public File[] getExportFiles() {
diff --git a/xml/impl/src/com/intellij/codeInsight/actions/GenerateDTDAction.java b/xml/impl/src/com/intellij/codeInsight/actions/GenerateDTDAction.java
index 027bb15ac45b..0c9c6d70183d 100644
--- a/xml/impl/src/com/intellij/codeInsight/actions/GenerateDTDAction.java
+++ b/xml/impl/src/com/intellij/codeInsight/actions/GenerateDTDAction.java
@@ -16,12 +16,17 @@
package com.intellij.codeInsight.actions;
import com.intellij.codeInsight.CodeInsightActionHandler;
-import com.intellij.openapi.actionSystem.*;
+import com.intellij.lang.xml.XMLLanguage;
+import com.intellij.openapi.actionSystem.ActionPlaces;
+import com.intellij.openapi.actionSystem.AnActionEvent;
+import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.psi.*;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.PsiFileFactory;
+import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
@@ -38,7 +43,6 @@ import org.jetbrains.annotations.Nullable;
* User: ik
* Date: 22.05.2003
* Time: 13:46:54
- * To change this template use Options | File Templates.
*/
public class GenerateDTDAction extends BaseCodeInsightAction{
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.actions.GenerateDTDAction");
@@ -82,12 +86,9 @@ public class GenerateDTDAction extends BaseCodeInsightAction{
@Nullable
private static XmlDocument findSuitableXmlDocument(@Nullable PsiFile psiFile) {
if (psiFile instanceof XmlFile) {
- final VirtualFile virtualFile = psiFile.getVirtualFile();
- if (virtualFile != null && virtualFile.isWritable()) {
- final XmlDocument document = ((XmlFile)psiFile).getDocument();
- if (document != null && document.getRootTag() != null) {
- return document;
- }
+ final XmlDocument document = ((XmlFile)psiFile).getDocument();
+ if (document != null && document.getRootTag() != null) {
+ return document;
}
}
return null;
@@ -95,28 +96,13 @@ public class GenerateDTDAction extends BaseCodeInsightAction{
public void update(AnActionEvent event) {
super.update(event);
-
- final DataContext dataContext = event.getDataContext();
- final Presentation presentation = event.getPresentation();
- Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
- Project project = PlatformDataKeys.PROJECT.getData(dataContext);
-
- final boolean enabled;
- if (editor != null && project != null) {
- PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
- enabled = findSuitableXmlDocument(file) != null;
- }
- else {
- enabled = false;
- }
-
- presentation.setEnabled(enabled);
if (ActionPlaces.isPopupPlace(event.getPlace())) {
- presentation.setVisible(enabled);
+ Presentation presentation = event.getPresentation();
+ presentation.setVisible(presentation.isEnabled());
}
}
protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file){
- return file instanceof XmlFile;
+ return file.getLanguage() == XMLLanguage.INSTANCE && findSuitableXmlDocument(file) != null;
}
}
diff --git a/xml/impl/src/com/intellij/codeInsight/completion/XmlSmartEnterProcessor.java b/xml/impl/src/com/intellij/codeInsight/completion/XmlSmartEnterProcessor.java
index 001f33948182..108ba0951aef 100644
--- a/xml/impl/src/com/intellij/codeInsight/completion/XmlSmartEnterProcessor.java
+++ b/xml/impl/src/com/intellij/codeInsight/completion/XmlSmartEnterProcessor.java
@@ -86,11 +86,12 @@ public class XmlSmartEnterProcessor extends SmartEnterProcessor {
final PsiElement element = psiFile.findElementAt(probableCommaOffset);
final XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
- final CharSequence text2insert = getClosingPart(xmlAttribute, tagAtCaret, false);
+ boolean shouldInsertClosingTag = shouldAfterWrapTextWithTag(caretAt, probableCommaOffset) || shouldInsertClosingTag(xmlAttribute, tagAtCaret);
+ final CharSequence text2insert = getClosingPart(xmlAttribute, tagAtCaret, !shouldInsertClosingTag);
if (tag != null && tag.getTextRange().getStartOffset() == probableCommaOffset) {
doc.insertString(caretAt, text2insert);
- if (shouldInsertClosingTag(xmlAttribute, tagAtCaret)) {
+ if (shouldInsertClosingTag) {
doc.insertString(tag.getTextRange().getEndOffset() + text2insert.length(), "</" + tagAtCaret.getName() + ">");
}
@@ -98,7 +99,7 @@ public class XmlSmartEnterProcessor extends SmartEnterProcessor {
}
else {
doc.insertString(caretAt, text2insert);
- if (shouldInsertClosingTag(xmlAttribute, tagAtCaret)) {
+ if (shouldInsertClosingTag) {
doc.insertString(probableCommaOffset + text2insert.length(), "</" + tagNameText + ">");
}
@@ -153,6 +154,10 @@ public class XmlSmartEnterProcessor extends SmartEnterProcessor {
return false;
}
+ protected boolean shouldAfterWrapTextWithTag(int caretAt, int probableCommaOffset) {
+ return probableCommaOffset > caretAt;
+ }
+
private void commitChanges(Project project, Editor editor, PsiFile psiFile, int caretOffset, @Nullable XmlTag tagToReformat) {
if (isUncommited(project)) {
commit(editor);
@@ -189,7 +194,7 @@ public class XmlSmartEnterProcessor extends SmartEnterProcessor {
}
protected boolean shouldInsertClosingTag(final XmlAttribute xmlAttribute, final XmlTag tagAtCaret) {
- return true;
+ return xmlAttribute == null || getClosingQuote(xmlAttribute).length() != 0;
}
protected String getClosingPart(final XmlAttribute xmlAttribute, final XmlTag tagAtCaret, final boolean emptyTag) {
diff --git a/xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java b/xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java
index a8ec5ee935ca..1f6b399f4b2f 100644
--- a/xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java
+++ b/xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java
@@ -27,12 +27,10 @@ import com.intellij.codeInsight.template.impl.MacroCallNode;
import com.intellij.codeInsight.template.macro.CompleteMacro;
import com.intellij.codeInsight.template.macro.CompleteSmartMacro;
import com.intellij.codeInspection.InspectionProfile;
-import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.codeInspection.htmlInspections.RequiredAttributesInspection;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.UndoManager;
-import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
@@ -57,7 +55,6 @@ import java.util.*;
public class XmlTagInsertHandler implements InsertHandler<LookupElement> {
- private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.XmlTagInsertHandler");
public static final XmlTagInsertHandler INSTANCE = new XmlTagInsertHandler();
public void handleInsert(InsertionContext context, LookupElement item) {
@@ -201,10 +198,8 @@ public class XmlTagInsertHandler implements InsertHandler<LookupElement> {
if (tag instanceof HtmlTag) {
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(tag.getProject()).getInspectionProfile();
- LocalInspectionToolWrapper localInspectionToolWrapper = (LocalInspectionToolWrapper) profile.getInspectionTool(
+ RequiredAttributesInspection inspection = (RequiredAttributesInspection)profile.getUnwrappedTool(
RequiredAttributesInspection.SHORT_NAME, tag);
- RequiredAttributesInspection inspection = localInspectionToolWrapper != null ?
- (RequiredAttributesInspection) localInspectionToolWrapper.getTool(): null;
if (inspection != null) {
StringTokenizer tokenizer = new StringTokenizer(inspection.getAdditionalEntries(0));
diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/AddSchemaPrefixIntention.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/AddSchemaPrefixIntention.java
index e7d65657d0b4..723ba6e14fa6 100644
--- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/AddSchemaPrefixIntention.java
+++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/AddSchemaPrefixIntention.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -86,7 +86,7 @@ public class AddSchemaPrefixIntention extends PsiElementBaseIntentionAction {
tag.accept(new XmlRecursiveElementVisitor() {
@Override
public void visitXmlTag(XmlTag tag) {
- if (namespace.equals(tag.getNamespace()) && tag.getNamespacePrefix().length() == 0) {
+ if (tag.getNamespace().equals(namespace) && tag.getNamespacePrefix().length() == 0) {
tags.add(tag);
}
super.visitXmlTag(tag);
@@ -109,7 +109,7 @@ public class AddSchemaPrefixIntention extends PsiElementBaseIntentionAction {
if (xmlElement instanceof XmlElement) {
final XmlTag tag = PsiTreeUtil.getParentOfType(xmlElement, XmlTag.class, false);
if (tag != null) {
- if (namespace.equals(tag.getNamespace())) {
+ if (tag.getNamespace().equals(namespace)) {
if (ref.getRangeInElement().getLength() == value.getValue().length()) { //no ns prefix
values.add(value);
}
diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ConvertSchemaPrefixToDefaultIntention.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ConvertSchemaPrefixToDefaultIntention.java
index 34c4809aa811..adfec6974ebc 100644
--- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ConvertSchemaPrefixToDefaultIntention.java
+++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ConvertSchemaPrefixToDefaultIntention.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -92,6 +92,7 @@ public class ConvertSchemaPrefixToDefaultIntention extends PsiElementBaseIntenti
}
}
for (XmlAttribute attr : attrs) {
+ //noinspection ConstantConditions
attr.setValue(attr.getValue().substring(index));
}
xmlns.setName("xmlns");
diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java
index cc56168ca95a..d4860becbf13 100644
--- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java
+++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java
@@ -26,7 +26,6 @@ import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixActionRegistrarImpl
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider;
import com.intellij.codeInspection.InspectionProfile;
-import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.codeInspection.htmlInspections.RequiredAttributesInspection;
import com.intellij.codeInspection.htmlInspections.XmlEntitiesInspection;
import com.intellij.lang.ASTNode;
@@ -321,10 +320,9 @@ public class XmlHighlightVisitor extends XmlElementVisitor implements HighlightV
tag, attrName, null);
final String localizedMessage = XmlErrorMessages.message("element.doesnt.have.required.attribute", name, attrName);
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(tag.getProject()).getInspectionProfile();
- final LocalInspectionToolWrapper toolWrapper =
- (LocalInspectionToolWrapper)profile.getInspectionTool(RequiredAttributesInspection.SHORT_NAME, tag);
- if (toolWrapper != null) {
- RequiredAttributesInspection inspection = (RequiredAttributesInspection)toolWrapper.getTool();
+ RequiredAttributesInspection inspection =
+ (RequiredAttributesInspection)profile.getUnwrappedTool(RequiredAttributesInspection.SHORT_NAME, tag);
+ if (inspection != null) {
reportOneTagProblem(
tag,
attrName,
diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FetchExtResourceAction.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FetchExtResourceAction.java
index 916f8f7eb730..c931ba5bff5f 100644
--- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FetchExtResourceAction.java
+++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FetchExtResourceAction.java
@@ -250,7 +250,7 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat
resourceUrls.add(s);
}
- final List<String> newLinks = extractEmbeddedFileReferences(virtualFile, contextFile, psiManager);
+ final Set<String> newLinks = extractEmbeddedFileReferences(virtualFile, contextFile, psiManager);
for (String u : newLinks) {
baseUrls.put(u, resourceUrl);
if (!processedLinks.contains(u)) linksToProcess.add(u);
@@ -390,8 +390,8 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat
return true;
}
- private static List<String> extractEmbeddedFileReferences(XmlFile file, XmlFile context) {
- final List<String> result = new LinkedList<String>();
+ private static Set<String> extractEmbeddedFileReferences(XmlFile file, XmlFile context) {
+ final Set<String> result = new LinkedHashSet<String>();
if (context != null) {
XmlEntityRefImpl.copyEntityCaches(file, context);
}
@@ -425,23 +425,13 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat
String schemaLocation = tag.getAttributeValue(XmlUtil.SCHEMA_LOCATION_ATT);
if (schemaLocation != null) {
- final PsiReference[] references = tag.getAttribute(XmlUtil.SCHEMA_LOCATION_ATT, null).getValueElement().getReferences();
+ final PsiReference[] references = tag.getAttribute(XmlUtil.SCHEMA_LOCATION_ATT).getValueElement().getReferences();
if (references.length > 0) {
- final String namespace = tag.getAttributeValue("namespace");
-
- if (namespace != null && schemaLocation.indexOf('/') == -1) {
- result.add(namespace.substring(0, namespace.lastIndexOf('/') + 1) + schemaLocation);
- }
- else {
- result.add(schemaLocation);
- }
+ result.add(schemaLocation);
}
}
-
- final String prefix = tag.getPrefixByNamespace(XmlUtil.XML_SCHEMA_INSTANCE_URI);
- if (prefix != null) {
+ else {
schemaLocation = tag.getAttributeValue("schemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);
-
if (schemaLocation != null) {
final StringTokenizer tokenizer = new StringTokenizer(schemaLocation);
@@ -449,10 +439,7 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat
tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) break;
String location = tokenizer.nextToken();
-
- if (!result.contains(location)) {
- result.add(location);
- }
+ result.add(location);
}
}
}
@@ -467,10 +454,10 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat
return result;
}
- public static List<String> extractEmbeddedFileReferences(final VirtualFile vFile, @Nullable final VirtualFile contextVFile, final PsiManager psiManager) {
- return ApplicationManager.getApplication().runReadAction(new Computable<List<String>>() {
+ public static Set<String> extractEmbeddedFileReferences(final VirtualFile vFile, @Nullable final VirtualFile contextVFile, final PsiManager psiManager) {
+ return ApplicationManager.getApplication().runReadAction(new Computable<Set<String>>() {
@Override
- public List<String> compute() {
+ public Set<String> compute() {
PsiFile file = psiManager.findFile(vFile);
if (file instanceof XmlFile) {
@@ -478,7 +465,7 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat
return extractEmbeddedFileReferences((XmlFile)file, contextFile instanceof XmlFile ? (XmlFile)contextFile : null);
}
- return Collections.emptyList();
+ return Collections.emptySet();
}
});
}
diff --git a/xml/impl/src/com/intellij/codeInsight/editorActions/moveUpDown/XmlMover.java b/xml/impl/src/com/intellij/codeInsight/editorActions/moveUpDown/XmlMover.java
index 3ef95edafd2f..09fb4a06bd14 100644
--- a/xml/impl/src/com/intellij/codeInsight/editorActions/moveUpDown/XmlMover.java
+++ b/xml/impl/src/com/intellij/codeInsight/editorActions/moveUpDown/XmlMover.java
@@ -108,7 +108,7 @@ class XmlMover extends LineMover {
final TextRange moveDestinationRange = new TextRange(
document.getLineStartOffset(info.toMove2.startLine),
- document.getLineStartOffset(info.toMove2.endLine) - 1
+ document.getLineEndOffset(info.toMove2.endLine - 1)
);
if (movedParent instanceof XmlAttribute) {
diff --git a/xml/impl/src/com/intellij/codeInsight/intentions/XmlChooseColorIntentionAction.java b/xml/impl/src/com/intellij/codeInsight/intentions/XmlChooseColorIntentionAction.java
index e92d59bdb5e9..1c0f5aa6986d 100644
--- a/xml/impl/src/com/intellij/codeInsight/intentions/XmlChooseColorIntentionAction.java
+++ b/xml/impl/src/com/intellij/codeInsight/intentions/XmlChooseColorIntentionAction.java
@@ -32,6 +32,7 @@ import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.ui.ColorChooser;
import com.intellij.ui.ColorUtil;
+import com.intellij.ui.JBColor;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
@@ -65,25 +66,26 @@ public class XmlChooseColorIntentionAction extends PsiElementBaseIntentionAction
final XmlAttributeValue literal = PsiTreeUtil.getParentOfType(element, XmlAttributeValue.class, false);
if (literal == null) return;
final String text = StringUtil.unquoteString(literal.getValue());
- final String hexPrefix = text.startsWith("#") ? "#" : "";
Color oldColor;
try {
oldColor = Color.decode(text);
}
catch (NumberFormatException e) {
- oldColor = Color.GRAY;
+ oldColor = JBColor.GRAY;
}
Color color = ColorChooser.chooseColor(editorComponent, caption, oldColor, true);
if (color == null) return;
if (!Comparing.equal(color, oldColor)) {
if (!CodeInsightUtilBase.preparePsiElementForWrite(element)) return;
- final String newText = hexPrefix + ColorUtil.toHex(color);
+ final String newText = "#" + ColorUtil.toHex(color);
final PsiManager manager = literal.getManager();
final XmlAttribute newAttribute = XmlElementFactory.getInstance(manager.getProject()).createXmlAttribute("name", newText);
final Runnable replaceRunnable = new Runnable() {
public void run() {
- literal.replace(newAttribute.getValueElement());
+ final XmlAttributeValue valueElement = newAttribute.getValueElement();
+ assert valueElement != null;
+ literal.replace(valueElement);
}
};
if (startInWriteAction) {
diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/XmlEmmetParser.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/XmlEmmetParser.java
index b8c5367e8fdf..803b955a41ed 100644
--- a/xml/impl/src/com/intellij/codeInsight/template/emmet/XmlEmmetParser.java
+++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/XmlEmmetParser.java
@@ -349,6 +349,10 @@ public class XmlEmmetParser extends EmmetParser {
final String name = ((IdentifierToken)token).getText();
+ if (name.isEmpty()) {
+ return null;
+ }
+
advance();
token = getToken();
if (token != ZenCodingTokens.EQ) {
diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java
index 3e2280e1de13..b945ca3fdd92 100644
--- a/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java
+++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java
@@ -197,6 +197,10 @@ public class ZenCodingTemplate implements CustomLiveTemplate {
GenerationNode genNode = genNodes.get(i);
TemplateImpl template = genNode.generate(callback, generator, filters, true);
int e = builder.insertTemplate(builder.length(), template, null);
+ if (i < genNodesSize - 1 && genNode.isInsertNewLineBetweenNodes()) {
+ builder.insertText(e, "\n", false);
+ e++;
+ }
if (end == -1 && end < builder.length()) {
end = e;
}
diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/generators/XmlZenCodingGeneratorImpl.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/generators/XmlZenCodingGeneratorImpl.java
index 2fbfc13be583..d595af8403f6 100644
--- a/xml/impl/src/com/intellij/codeInsight/template/emmet/generators/XmlZenCodingGeneratorImpl.java
+++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/generators/XmlZenCodingGeneratorImpl.java
@@ -107,7 +107,7 @@ public class XmlZenCodingGeneratorImpl extends XmlZenCodingGenerator {
@Override
public void visitXmlTag(final XmlTag tag) {
if (!isTagClosed(tag)) {
- tagToClose.add(pointerManager.createLazyPointer(tag));
+ tagToClose.add(pointerManager.createSmartPsiElementPointer(tag));
}
}
});
diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/nodes/GenerationNode.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/nodes/GenerationNode.java
index 031ed23394ae..e31b36ccb00b 100644
--- a/xml/impl/src/com/intellij/codeInsight/template/emmet/nodes/GenerationNode.java
+++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/nodes/GenerationNode.java
@@ -32,6 +32,7 @@ import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.UserDataHolderBase;
+import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
@@ -61,24 +62,39 @@ public class GenerationNode extends UserDataHolderBase {
private final int myTotalIterations;
private String mySurroundedText;
private final boolean myInsertSurroundedTextAtTheEnd;
- private GenerationNode myParent;
+ private final boolean myInsertNewLineBetweenNodes;
+
+ private GenerationNode myParent;
private boolean myContainsSurroundedTextMarker = false;
public GenerationNode(TemplateToken templateToken,
int numberInIteration,
int totalIterations, String surroundedText,
boolean insertSurroundedTextAtTheEnd, GenerationNode parent) {
+ this(templateToken, numberInIteration, totalIterations, surroundedText, insertSurroundedTextAtTheEnd, parent, false);
+ }
+
+
+ public GenerationNode(TemplateToken templateToken,
+ int numberInIteration,
+ int totalIterations, String surroundedText,
+ boolean insertSurroundedTextAtTheEnd, GenerationNode parent, boolean insertNewLineBetweenNodes) {
myTemplateToken = templateToken;
myNumberInIteration = numberInIteration;
myTotalIterations = totalIterations;
mySurroundedText = surroundedText;
myInsertSurroundedTextAtTheEnd = insertSurroundedTextAtTheEnd;
+ myInsertNewLineBetweenNodes = insertNewLineBetweenNodes;
if(parent != null) {
parent.addChild(this);
}
}
+ public boolean isInsertNewLineBetweenNodes() {
+ return myInsertNewLineBetweenNodes;
+ }
+
public List<GenerationNode> getChildren() {
return myChildren;
}
@@ -181,12 +197,8 @@ public class GenerationNode extends UserDataHolderBase {
indentStr = "\t";
}
else {
- StringBuilder tab = new StringBuilder();
int tabSize = settings.getTabSize(callback.getFileType());
- while (tabSize-- > 0) {
- tab.append(' ');
- }
- indentStr = tab.toString();
+ indentStr = StringUtil.repeatSymbol(' ', tabSize);
}
for (int i = 0, myChildrenSize = myChildren.size(); i < myChildrenSize; i++) {
@@ -203,7 +215,7 @@ public class GenerationNode extends UserDataHolderBase {
int e = builder.insertTemplate(offset, childTemplate, null);
offset = marker != null ? marker.getEndOffset() : builder.length();
- if (!singleLineFilterEnabled && blockTag && !isNewLineAfter(builder.getText(), offset)) {
+ if (!singleLineFilterEnabled && ((blockTag && !isNewLineAfter(builder.getText(), offset)) || myInsertNewLineBetweenNodes)) {
builder.insertText(offset, "\n" + indentStr, false);
offset += indentStr.length() + 1;
}
diff --git a/xml/impl/src/com/intellij/codeInspection/htmlInspections/AddCustomTagOrAttributeIntentionAction.java b/xml/impl/src/com/intellij/codeInspection/htmlInspections/AddCustomTagOrAttributeIntentionAction.java
index ce0d01ef3cc2..ba84b96d3f62 100644
--- a/xml/impl/src/com/intellij/codeInspection/htmlInspections/AddCustomTagOrAttributeIntentionAction.java
+++ b/xml/impl/src/com/intellij/codeInspection/htmlInspections/AddCustomTagOrAttributeIntentionAction.java
@@ -16,10 +16,11 @@
package com.intellij.codeInspection.htmlInspections;
+import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.LocalQuickFix;
-import com.intellij.codeInspection.ModifiableModel;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Key;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.PsiElement;
import com.intellij.util.Consumer;
@@ -32,10 +33,10 @@ import org.jetbrains.annotations.NotNull;
public class AddCustomTagOrAttributeIntentionAction implements LocalQuickFix {
private final String myName;
private final int myType;
- private final String myInspectionName;
+ @NotNull private final Key<HtmlUnknownTagInspection> myInspectionKey;
- public AddCustomTagOrAttributeIntentionAction(@NotNull String shortName, String name, int type) {
- myInspectionName = shortName;
+ public AddCustomTagOrAttributeIntentionAction(@NotNull Key<HtmlUnknownTagInspection> inspectionKey, String name, int type) {
+ myInspectionKey = inspectionKey;
myName = name;
myType = type;
}
@@ -65,10 +66,10 @@ public class AddCustomTagOrAttributeIntentionAction implements LocalQuickFix {
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
final PsiElement element = descriptor.getPsiElement();
- InspectionProjectProfileManager.getInstance(project).getInspectionProfile().modifyProfile(new Consumer<ModifiableModel>() {
+ InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
+ profile.modifyToolSettings(myInspectionKey, element, new Consumer<HtmlUnknownTagInspection>() {
@Override
- public void consume(ModifiableModel model) {
- HtmlUnknownTagInspection tool = (HtmlUnknownTagInspection)model.getUnwrappedTool(myInspectionName, element);
+ public void consume(HtmlUnknownTagInspection tool) {
tool.addCustomPropertyName(myName);
}
});
diff --git a/xml/impl/src/com/intellij/codeInspection/htmlInspections/AddHtmlTagOrAttributeToCustomsIntention.java b/xml/impl/src/com/intellij/codeInspection/htmlInspections/AddHtmlTagOrAttributeToCustomsIntention.java
index 63be9c5ab72d..78366a2c0ab1 100644
--- a/xml/impl/src/com/intellij/codeInspection/htmlInspections/AddHtmlTagOrAttributeToCustomsIntention.java
+++ b/xml/impl/src/com/intellij/codeInspection/htmlInspections/AddHtmlTagOrAttributeToCustomsIntention.java
@@ -17,9 +17,11 @@
package com.intellij.codeInspection.htmlInspections;
import com.intellij.codeInsight.intention.IntentionAction;
-import com.intellij.codeInspection.ModifiableModel;
+import com.intellij.codeInspection.InspectionProfile;
+import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Key;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.PsiFile;
import com.intellij.util.Consumer;
@@ -33,10 +35,10 @@ import org.jetbrains.annotations.NotNull;
public class AddHtmlTagOrAttributeToCustomsIntention implements IntentionAction {
private final String myName;
private final int myType;
- private final String myInspectionName;
+ private final Key<InspectionProfileEntry> myInspectionKey;
- public AddHtmlTagOrAttributeToCustomsIntention(String shortName, String name, int type) {
- myInspectionName = shortName;
+ public AddHtmlTagOrAttributeToCustomsIntention(Key<InspectionProfileEntry> inspectionKey, String name, int type) {
+ myInspectionKey = inspectionKey;
myName = name;
myType = type;
}
@@ -68,10 +70,11 @@ public class AddHtmlTagOrAttributeToCustomsIntention implements IntentionAction
}
public void invoke(@NotNull Project project, Editor editor, final PsiFile file) throws IncorrectOperationException {
- InspectionProjectProfileManager.getInstance(project).getInspectionProfile().modifyProfile(new Consumer<ModifiableModel>() {
+ InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
+ profile.modifyToolSettings(myInspectionKey, file, new Consumer<InspectionProfileEntry>() {
@Override
- public void consume(ModifiableModel model) {
- XmlEntitiesInspection xmlEntitiesInspection = (XmlEntitiesInspection)model.getUnwrappedTool(myInspectionName, file);
+ public void consume(InspectionProfileEntry entry) {
+ XmlEntitiesInspection xmlEntitiesInspection = (XmlEntitiesInspection) entry;
xmlEntitiesInspection.setAdditionalEntries(myType, appendName(xmlEntitiesInspection.getAdditionalEntries(myType)));
}
});
diff --git a/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownAttributeInspection.java b/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownAttributeInspection.java
index 9dac096fc6db..58617e8d1b29 100644
--- a/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownAttributeInspection.java
+++ b/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownAttributeInspection.java
@@ -22,6 +22,7 @@ import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiElement;
import com.intellij.psi.html.HtmlTag;
import com.intellij.psi.xml.XmlAttribute;
@@ -44,6 +45,7 @@ public class HtmlUnknownAttributeInspection extends HtmlUnknownTagInspection {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.htmlInspections.HtmlUnknownAttributeInspection");
@NonNls public static final String ATTRIBUTE_SHORT_NAME = "HtmlUnknownAttribute";
+ public static final Key<HtmlUnknownTagInspection> ATTRIBUTE_KEY = Key.create(ATTRIBUTE_SHORT_NAME);
public HtmlUnknownAttributeInspection() {
super("");
@@ -100,7 +102,7 @@ public class HtmlUnknownAttributeInspection extends HtmlUnknownTagInspection {
boolean maySwitchToHtml5 = HtmlUtil.isCustomHtml5Attribute(name) && !HtmlUtil.hasNonHtml5Doctype(tag);
LocalQuickFix[] quickfixes = new LocalQuickFix[maySwitchToHtml5 ? 3 : 2];
- quickfixes[0] = new AddCustomTagOrAttributeIntentionAction(getShortName(), name, XmlEntitiesInspection.UNKNOWN_ATTRIBUTE);
+ quickfixes[0] = new AddCustomTagOrAttributeIntentionAction(ATTRIBUTE_KEY, name, XmlEntitiesInspection.UNKNOWN_ATTRIBUTE);
quickfixes[1] = new RemoveAttributeIntentionAction(name);
if (maySwitchToHtml5) {
quickfixes[2] = new SwitchToHtml5WithHighPriorityAction();
diff --git a/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownTagInspection.java b/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownTagInspection.java
index 08ab3339463f..38a54cd7d944 100644
--- a/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownTagInspection.java
+++ b/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownTagInspection.java
@@ -24,6 +24,7 @@ import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.JDOMExternalizableStringList;
+import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiElement;
import com.intellij.psi.html.HtmlTag;
import com.intellij.psi.impl.source.html.dtd.HtmlElementDescriptorImpl;
@@ -43,7 +44,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
-import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
@@ -63,6 +63,7 @@ public class HtmlUnknownTagInspection extends HtmlLocalInspectionTool {
public JDOMExternalizableStringList myValues;
public boolean myCustomValuesEnabled = true;
@NonNls public static final String TAG_SHORT_NAME = "HtmlUnknownTag";
+ public static final Key<HtmlUnknownTagInspection> TAG_KEY = Key.create(TAG_SHORT_NAME);
public HtmlUnknownTagInspection() {
this("nobr,noembed,comment,noscript,embed,script");
@@ -229,7 +230,7 @@ public class HtmlUnknownTagInspection extends HtmlLocalInspectionTool {
if (!isCustomValuesEnabled() || !isCustomValue(name)) {
final AddCustomTagOrAttributeIntentionAction action =
- new AddCustomTagOrAttributeIntentionAction(getShortName(), name, XmlEntitiesInspection.UNKNOWN_TAG);
+ new AddCustomTagOrAttributeIntentionAction(TAG_KEY, name, XmlEntitiesInspection.UNKNOWN_TAG);
// todo: support "element is not allowed" message for html5
// some tags in html5 cannot be found in xhtml5.xsd if they are located in incorrect context, so they get any-element descriptor (ex. "canvas: tag)
diff --git a/xml/impl/src/com/intellij/codeInspection/htmlInspections/RequiredAttributesInspection.java b/xml/impl/src/com/intellij/codeInspection/htmlInspections/RequiredAttributesInspection.java
index d4cdffe1d274..bde145d007a8 100644
--- a/xml/impl/src/com/intellij/codeInspection/htmlInspections/RequiredAttributesInspection.java
+++ b/xml/impl/src/com/intellij/codeInspection/htmlInspections/RequiredAttributesInspection.java
@@ -16,11 +16,13 @@
package com.intellij.codeInspection.htmlInspections;
import com.intellij.codeInsight.intention.IntentionAction;
+import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.InspectionsBundle;
-import com.intellij.codeInspection.XmlSuppressableInspectionTool;
import com.intellij.codeInspection.XmlInspectionGroupNames;
+import com.intellij.codeInspection.XmlSuppressableInspectionTool;
import com.intellij.codeInspection.ex.UnfairLocalInspectionTool;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.Key;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.FieldPanel;
import org.jetbrains.annotations.NonNls;
@@ -43,6 +45,7 @@ public class RequiredAttributesInspection extends XmlSuppressableInspectionTool
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.htmlInspections.RequiredAttributesInspection");
@NonNls public static final String SHORT_NAME = "RequiredAttributes";
+ @NonNls public static final Key<InspectionProfileEntry> SHORT_NAME_KEY = Key.create(SHORT_NAME);
@NotNull
public String getGroupDisplayName() {
@@ -87,7 +90,7 @@ public class RequiredAttributesInspection extends XmlSuppressableInspectionTool
}
public IntentionAction getIntentionAction(String name, int type) {
- return new AddHtmlTagOrAttributeToCustomsIntention(getShortName(), name, type);
+ return new AddHtmlTagOrAttributeToCustomsIntention(SHORT_NAME_KEY, name, type);
}
public String getAdditionalEntries(int type) {
diff --git a/xml/impl/src/com/intellij/javaee/ExternalResourceManagerImpl.java b/xml/impl/src/com/intellij/javaee/ExternalResourceManagerImpl.java
index de54dc37e24c..fb7e632de572 100644
--- a/xml/impl/src/com/intellij/javaee/ExternalResourceManagerImpl.java
+++ b/xml/impl/src/com/intellij/javaee/ExternalResourceManagerImpl.java
@@ -94,7 +94,7 @@ public class ExternalResourceManagerImpl extends ExternalResourceManagerEx imple
return registrar.getResources();
}
- private final List<ExternalResourceListener> myListeners = new ArrayList<ExternalResourceListener>();
+ private final List<ExternalResourceListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private long myModificationCount = 0;
private final PathMacrosImpl myPathMacros;
@NonNls private static final String RESOURCE_ELEMENT = "resource";
@@ -437,7 +437,7 @@ public class ExternalResourceManagerImpl extends ExternalResourceManagerEx imple
}
private void fireExternalResourceChanged() {
- for (ExternalResourceListener listener : myListeners.toArray(new ExternalResourceListener[myListeners.size()])) {
+ for (ExternalResourceListener listener : myListeners) {
listener.externalResourceChanged();
}
}
diff --git a/xml/impl/src/com/intellij/javaee/HtmlLanguageLevelForm.java b/xml/impl/src/com/intellij/javaee/HtmlLanguageLevelForm.java
index 5f319306c598..ac828cbf5b88 100644
--- a/xml/impl/src/com/intellij/javaee/HtmlLanguageLevelForm.java
+++ b/xml/impl/src/com/intellij/javaee/HtmlLanguageLevelForm.java
@@ -19,6 +19,7 @@ import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.project.Project;
import com.intellij.ui.TextFieldWithAutoCompletion;
+import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.xml.Html5SchemaProvider;
import com.intellij.xml.util.XmlUtil;
@@ -27,7 +28,6 @@ import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -41,7 +41,7 @@ public class HtmlLanguageLevelForm {
private JPanel myContentPanel;
private JPanel myOtherDoctypeWrapper;
private final TextFieldWithAutoCompletion myDoctypeTextField;
- private final List<MyListener> myListeners = new ArrayList<MyListener>();
+ private final List<MyListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
public HtmlLanguageLevelForm(Project project) {
final String[] urls = ExternalResourceManager.getInstance().getResourceUrls(null, true);
diff --git a/xml/impl/src/com/intellij/lang/html/structureView/Html5SectionsNodeProvider.java b/xml/impl/src/com/intellij/lang/html/structureView/Html5SectionsNodeProvider.java
index 49ad3fbba26e..a1cbc3555a89 100644
--- a/xml/impl/src/com/intellij/lang/html/structureView/Html5SectionsNodeProvider.java
+++ b/xml/impl/src/com/intellij/lang/html/structureView/Html5SectionsNodeProvider.java
@@ -15,6 +15,7 @@
*/
package com.intellij.lang.html.structureView;
+import com.intellij.icons.AllIcons;
import com.intellij.ide.util.FileStructureNodeProvider;
import com.intellij.ide.util.treeView.smartTree.ActionPresentation;
import com.intellij.ide.util.treeView.smartTree.ActionPresentationData;
@@ -47,7 +48,7 @@ public class Html5SectionsNodeProvider implements FileStructureNodeProvider<Html
@NotNull
public ActionPresentation getPresentation() {
- return new ActionPresentationData(XmlBundle.message("html5.outline.mode"), null, null);
+ return new ActionPresentationData(XmlBundle.message("html5.outline.mode"), null, AllIcons.Xml.Html5);
}
public String getCheckBoxText() {
diff --git a/xml/impl/src/com/intellij/psi/formatter/xml/AbstractXmlBlock.java b/xml/impl/src/com/intellij/psi/formatter/xml/AbstractXmlBlock.java
index 4609f73e79fc..8b602e1b51a7 100644
--- a/xml/impl/src/com/intellij/psi/formatter/xml/AbstractXmlBlock.java
+++ b/xml/impl/src/com/intellij/psi/formatter/xml/AbstractXmlBlock.java
@@ -22,6 +22,7 @@ import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
+import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.formatter.WhiteSpaceFormattingStrategy;
import com.intellij.psi.formatter.WhiteSpaceFormattingStrategyFactory;
import com.intellij.psi.formatter.common.AbstractBlock;
@@ -61,9 +62,6 @@ public abstract class AbstractXmlBlock extends AbstractBlock {
final boolean preserveSpace) {
super(node, wrap, alignment);
myXmlFormattingPolicy = policy;
- if (node == null) {
- LOG.assertTrue(false);
- }
if (node.getTreeParent() == null) {
myXmlFormattingPolicy.setRootBlock(node, this);
}
@@ -105,9 +103,9 @@ public abstract class AbstractXmlBlock extends AbstractBlock {
public static WrapType getWrapType(final int type) {
- if (type == CodeStyleSettings.DO_NOT_WRAP) return WrapType.NONE;
- if (type == CodeStyleSettings.WRAP_ALWAYS) return WrapType.ALWAYS;
- if (type == CodeStyleSettings.WRAP_AS_NEEDED) return WrapType.NORMAL;
+ if (type == CommonCodeStyleSettings.DO_NOT_WRAP) return WrapType.NONE;
+ if (type == CommonCodeStyleSettings.WRAP_ALWAYS) return WrapType.ALWAYS;
+ if (type == CommonCodeStyleSettings.WRAP_AS_NEEDED) return WrapType.NORMAL;
return WrapType.CHOP_DOWN_IF_LONG;
}
@@ -127,8 +125,8 @@ public abstract class AbstractXmlBlock extends AbstractBlock {
if (myNode.getElementType() == XmlElementType.XML_TEXT) return textWrap;
final IElementType elementType = child.getElementType();
if (elementType == XmlElementType.XML_ATTRIBUTE) return attrWrap;
- if (elementType == XmlElementType.XML_START_TAG_START) return tagBeginWrap;
- if (elementType == XmlElementType.XML_END_TAG_START) {
+ if (elementType == XmlTokenType.XML_START_TAG_START) return tagBeginWrap;
+ if (elementType == XmlTokenType.XML_END_TAG_START) {
final PsiElement parent = SourceTreeToPsiMap.treeElementToPsi(child.getTreeParent());
if (parent instanceof XmlTag) {
final XmlTag tag = (XmlTag)parent;
@@ -138,7 +136,7 @@ public abstract class AbstractXmlBlock extends AbstractBlock {
}
return null;
}
- if (elementType == XmlElementType.XML_TEXT || elementType == XmlElementType.XML_DATA_CHARACTERS) return textWrap;
+ if (elementType == XmlElementType.XML_TEXT || elementType == XmlTokenType.XML_DATA_CHARACTERS) return textWrap;
return null;
}
@@ -273,7 +271,7 @@ public abstract class AbstractXmlBlock extends AbstractBlock {
final Indent indent) {
ASTNode resultNode = child;
ASTNode currentChild = child.getTreeNext();
- while (currentChild != null && currentChild.getElementType() != XmlElementType.XML_END_TAG_START) {
+ while (currentChild != null && currentChild.getElementType() != XmlTokenType.XML_END_TAG_START) {
if (!containsWhiteSpacesOnly(currentChild)) {
currentChild = processChild(result, currentChild, wrap, alignment, indent);
resultNode = currentChild;
@@ -297,7 +295,8 @@ public abstract class AbstractXmlBlock extends AbstractBlock {
new XmlBlock(child, wrap, alignment, myXmlFormattingPolicy, indent, null, isPreserveSpace()) {
protected Wrap getDefaultWrap(final ASTNode node) {
final IElementType type = node.getElementType();
- return type == XmlElementType.XML_ATTRIBUTE_VALUE_TOKEN ? Wrap.createWrap(getWrapType(myXmlFormattingPolicy.getAttributesWrap()), false) : null;
+ return type == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN
+ ? Wrap.createWrap(getWrapType(myXmlFormattingPolicy.getAttributesWrap()), false) : null;
}
}
);
@@ -415,8 +414,8 @@ public abstract class AbstractXmlBlock extends AbstractBlock {
public boolean isLeaf() {
return (isComment(myNode)) ||
myNode.getElementType() == TokenType.WHITE_SPACE ||
- myNode.getElementType() == XmlElementType.XML_DATA_CHARACTERS ||
- myNode.getElementType() == XmlElementType.XML_ATTRIBUTE_VALUE_TOKEN;
+ myNode.getElementType() == XmlTokenType.XML_DATA_CHARACTERS ||
+ myNode.getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN;
}
private static boolean isComment(final ASTNode node) {
@@ -460,11 +459,11 @@ public abstract class AbstractXmlBlock extends AbstractBlock {
}
public boolean isCDATAStart() {
- return myNode.getElementType() == XmlElementType.XML_CDATA_START;
+ return myNode.getElementType() == XmlTokenType.XML_CDATA_START;
}
public boolean isCDATAEnd() {
- return myNode.getElementType() == XmlElementType.XML_CDATA_END;
+ return myNode.getElementType() == XmlTokenType.XML_CDATA_END;
}
public static boolean containsWhiteSpacesOnly(ASTNode node) {
diff --git a/xml/impl/src/com/intellij/psi/formatter/xml/XmlBlock.java b/xml/impl/src/com/intellij/psi/formatter/xml/XmlBlock.java
index f4a6dc528b95..89be0169aeeb 100644
--- a/xml/impl/src/com/intellij/psi/formatter/xml/XmlBlock.java
+++ b/xml/impl/src/com/intellij/psi/formatter/xml/XmlBlock.java
@@ -91,28 +91,22 @@ public class XmlBlock extends AbstractXmlBlock {
return result;
}
return splitComment();
- }
-
- if (myNode.getElementType() == XmlElementType.XML_TEXT) {
- if (myXmlFormattingPolicy.getShouldKeepWhiteSpaces()) {
- return EMPTY;
- }
-
- final ASTNode treeParent = myNode.getTreeParent();
- final XmlTag tag = getTag(treeParent);
- if (tag != null) {
- if (myXmlFormattingPolicy.keepWhiteSpacesInsideTag(tag)) {
- return EMPTY;
- }
- }
- }
+ }
if (myNode.getFirstChildNode() != null) {
+ boolean keepWhitespaces = shouldKeepWhitespaces();
final ArrayList<Block> result = new ArrayList<Block>(5);
ASTNode child = myNode.getFirstChildNode();
while (child != null) {
- if (!containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
- child = processChild(result, child, getDefaultWrap(child), null, getChildDefaultIndent());
+ if (child.getTextLength() > 0) {
+ if (containsWhiteSpacesOnly(child)) {
+ if (keepWhitespaces) {
+ result.add(new ReadOnlyBlock(child));
+ }
+ }
+ else {
+ child = processChild(result, child, getDefaultWrap(child), null, getChildDefaultIndent());
+ }
}
if (child != null) {
LOG.assertTrue(child.getTreeParent() == myNode);
@@ -126,6 +120,24 @@ public class XmlBlock extends AbstractXmlBlock {
}
}
+ private boolean shouldKeepWhitespaces() {
+ if (myNode.getElementType() == XmlElementType.XML_TEXT) {
+ if (myXmlFormattingPolicy.getShouldKeepWhiteSpaces()) {
+ return true;
+ }
+ else {
+ final ASTNode treeParent = myNode.getTreeParent();
+ final XmlTag tag = getTag(treeParent);
+ if (tag != null) {
+ if (myXmlFormattingPolicy.keepWhiteSpacesInsideTag(tag)) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
private List<Block> splitAttribute(ASTNode node, XmlFormattingPolicy formattingPolicy) {
final ArrayList<Block> result = new ArrayList<Block>(3);
diff --git a/xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/URIReferenceProvider.java b/xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/URIReferenceProvider.java
index 5c8eb583f01e..23ab5613fe7b 100644
--- a/xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/URIReferenceProvider.java
+++ b/xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/URIReferenceProvider.java
@@ -78,14 +78,9 @@ public class URIReferenceProvider extends PsiReferenceProvider {
}
@Nullable
- public PsiFile resolveResource() {
- final String canonicalText = getCanonicalText();
- return ExternalResourceManager.getInstance().getResourceLocation(canonicalText, myElement.getContainingFile(), null);
- }
-
- @Nullable
public PsiElement resolve() {
- final PsiFile file = resolveResource();
+ final String canonicalText = getCanonicalText();
+ final PsiFile file = ExternalResourceManager.getInstance().getResourceLocation(canonicalText, myElement.getContainingFile(), null);
if (file != null) return file;
return myReference.resolve();
}
@@ -112,7 +107,9 @@ public class URIReferenceProvider extends PsiReferenceProvider {
String s = StringUtil.stripQuotesAroundValue(text);
final PsiElement parent = element.getParent();
- if (parent instanceof XmlAttribute && "xsi:schemaLocation".equals(((XmlAttribute)parent).getName())) {
+ if (parent instanceof XmlAttribute &&
+ XmlUtil.SCHEMA_LOCATION_ATT.equals(((XmlAttribute)parent).getLocalName()) &&
+ XmlUtil.XML_SCHEMA_INSTANCE_URI.equals(((XmlAttribute)parent).getNamespace())) {
final List<PsiReference> refs = new ArrayList<PsiReference>(2);
final StringTokenizer tokenizer = new StringTokenizer(s);
diff --git a/xml/impl/src/com/intellij/psi/impl/source/xml/TagNameReference.java b/xml/impl/src/com/intellij/psi/impl/source/xml/TagNameReference.java
index be38440de4d6..de520f9add66 100644
--- a/xml/impl/src/com/intellij/psi/impl/source/xml/TagNameReference.java
+++ b/xml/impl/src/com/intellij/psi/impl/source/xml/TagNameReference.java
@@ -21,6 +21,7 @@ import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.lookup.TailTypeDecorator;
+import com.intellij.html.impl.RelaxedHtmlFromSchemaElementDescriptor;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
@@ -288,7 +289,10 @@ public class TagNameReference implements PsiReference {
context instanceof XmlTag ? (XmlTag)context : element, extension);
if (nsInfo != null) {
for (int i = initialSize; i < variants.size(); i++) {
- nsInfo.add(namespace);
+ XmlElementDescriptor descriptor = variants.get(i);
+ nsInfo.add(descriptor instanceof XmlElementDescriptorImpl && !(descriptor instanceof RelaxedHtmlFromSchemaElementDescriptor)
+ ? ((XmlElementDescriptorImpl)descriptor).getNamespaceByContext(element)
+ : namespace);
}
}
}
@@ -299,7 +303,7 @@ public class TagNameReference implements PsiReference {
if (descriptor instanceof AnyXmlElementDescriptor) {
return null;
}
- else if (hasPrefix && descriptor instanceof XmlElementDescriptorImpl &&
+ else if (hasPrefix && descriptor instanceof XmlElementDescriptorImpl &&
!namespaces.contains(((XmlElementDescriptorImpl)descriptor).getNamespace())) {
return null;
}
diff --git a/xml/impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java b/xml/impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java
index e9773014b980..45e41d36fc73 100644
--- a/xml/impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java
+++ b/xml/impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java
@@ -295,7 +295,7 @@ public class XmlTagImpl extends XmlElementImpl implements XmlTag {
while (tokenizer.hasMoreTokens()) {
final String uri = tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
- map = initializeSchema(uri, null, tokenizer.nextToken(), map);
+ map = initializeSchema(uri, getNSVersion(uri, this), tokenizer.nextToken(), map);
}
}
}
diff --git a/xml/impl/src/com/intellij/xml/DefaultXmlExtension.java b/xml/impl/src/com/intellij/xml/DefaultXmlExtension.java
index f024e874b2e7..1d1e28f12d7a 100644
--- a/xml/impl/src/com/intellij/xml/DefaultXmlExtension.java
+++ b/xml/impl/src/com/intellij/xml/DefaultXmlExtension.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -173,35 +173,23 @@ public class DefaultXmlExtension extends XmlExtension {
final String namespace = possibleNamespaces.iterator().next();
final Project project = file.getProject();
- final XmlDocument document = file.getDocument();
- assert document != null;
- final XmlTag rootTag = document.getRootTag();
+ final XmlTag rootTag = file.getRootTag();
assert rootTag != null;
- final XmlAttribute[] attributes = rootTag.getAttributes();
- XmlAttribute anchor = null;
- for (XmlAttribute attribute : attributes) {
- final XmlAttributeDescriptor descriptor = attribute.getDescriptor();
- if (attribute.isNamespaceDeclaration() || (descriptor != null && descriptor.isRequired())) {
- anchor = attribute;
- } else {
- break;
- }
- }
+ XmlAttribute anchor = getAnchor(rootTag);
final List<XmlSchemaProvider> providers = XmlSchemaProvider.getAvailableProviders(file);
- String prefix = nsPrefix;
- if (prefix == null) {
- for (XmlSchemaProvider provider : providers) {
- prefix = provider.getDefaultPrefix(namespace, file);
- if (prefix != null) {
- break;
- }
+ String prefix = getPrefix(file, nsPrefix, namespace, providers);
+
+ final XmlElementFactory elementFactory = XmlElementFactory.getInstance(project);
+ String location = getLocation(file, namespace, providers);
+ String xsiPrefix = null;
+ if (location != null) {
+ xsiPrefix = rootTag.getPrefixByNamespace(XmlUtil.XML_SCHEMA_INSTANCE_URI);
+ if (xsiPrefix == null) {
+ xsiPrefix = "xsi";
+ rootTag.add(elementFactory.createXmlAttribute("xmlns:xsi", XmlUtil.XML_SCHEMA_INSTANCE_URI));
}
}
- if (prefix == null) {
- prefix = "";
- }
- final XmlElementFactory elementFactory = XmlElementFactory.getInstance(project);
@NonNls final String qname = "xmlns" + (prefix.length() > 0 ? ":"+ prefix :"");
final XmlAttribute attribute = elementFactory.createXmlAttribute(qname, namespace);
@@ -211,29 +199,21 @@ public class DefaultXmlExtension extends XmlExtension {
rootTag.addAfter(attribute, anchor);
}
- String location = null;
- if (namespace.length() > 0) {
- for (XmlSchemaProvider provider : providers) {
- Set<String> locations = provider.getLocations(namespace, file);
- if (locations != null && !locations.isEmpty()) {
- location = locations.iterator().next();
- }
- }
- }
-
if (location != null) {
- XmlAttribute xmlAttribute = rootTag.getAttribute("xsi:schemaLocation");
+ XmlAttribute locationAttribute = rootTag.getAttribute(XmlUtil.SCHEMA_LOCATION_ATT, XmlUtil.XML_SCHEMA_INSTANCE_URI);
final String pair = namespace + " " + location;
- if (xmlAttribute == null) {
- xmlAttribute = elementFactory.createXmlAttribute("xsi:schemaLocation", pair);
- rootTag.add(xmlAttribute);
- } else {
- final String value = xmlAttribute.getValue();
- if (!value.contains(namespace)) {
- if (StringUtil.isEmptyOrSpaces(value)) {
- xmlAttribute.setValue(pair);
- } else {
- xmlAttribute.setValue(value.trim() + " " + pair);
+ if (locationAttribute == null) {
+ locationAttribute = elementFactory.createXmlAttribute(xsiPrefix + ":" + XmlUtil.SCHEMA_LOCATION_ATT, pair);
+ rootTag.add(locationAttribute);
+ }
+ else {
+ final String value = locationAttribute.getValue();
+ if (!StringUtil.notNullize(value).contains(namespace)) {
+ if (value == null || StringUtil.isEmptyOrSpaces(value)) {
+ locationAttribute.setValue(pair);
+ }
+ else {
+ locationAttribute.setValue(value.trim() + " " + pair);
}
}
}
@@ -255,6 +235,49 @@ public class DefaultXmlExtension extends XmlExtension {
}
}
+ private static String getPrefix(XmlFile file, String nsPrefix, String namespace, List<XmlSchemaProvider> providers) {
+ String prefix = nsPrefix;
+ if (prefix == null) {
+ for (XmlSchemaProvider provider : providers) {
+ prefix = provider.getDefaultPrefix(namespace, file);
+ if (prefix != null) {
+ break;
+ }
+ }
+ }
+ if (prefix == null) {
+ prefix = "";
+ }
+ return prefix;
+ }
+
+ private static XmlAttribute getAnchor(XmlTag rootTag) {
+ final XmlAttribute[] attributes = rootTag.getAttributes();
+ XmlAttribute anchor = null;
+ for (XmlAttribute attribute : attributes) {
+ final XmlAttributeDescriptor descriptor = attribute.getDescriptor();
+ if (attribute.isNamespaceDeclaration() || (descriptor != null && descriptor.isRequired())) {
+ anchor = attribute;
+ } else {
+ break;
+ }
+ }
+ return anchor;
+ }
+
+ private static String getLocation(XmlFile file, String namespace, List<XmlSchemaProvider> providers) {
+ String location = null;
+ if (namespace.length() > 0) {
+ for (XmlSchemaProvider provider : providers) {
+ Set<String> locations = provider.getLocations(namespace, file);
+ if (locations != null && !locations.isEmpty()) {
+ location = locations.iterator().next();
+ }
+ }
+ }
+ return location;
+ }
+
public SchemaPrefix getPrefixDeclaration(final XmlTag context, String namespacePrefix) {
@NonNls String nsDeclarationAttrName = null;
for(XmlTag t = context; t != null; t = t.getParentTag()) {
diff --git a/xml/impl/src/com/intellij/xml/arrangement/XmlArrangementVisitor.java b/xml/impl/src/com/intellij/xml/arrangement/XmlArrangementVisitor.java
index e455843ed7db..907ca9151988 100644
--- a/xml/impl/src/com/intellij/xml/arrangement/XmlArrangementVisitor.java
+++ b/xml/impl/src/com/intellij/xml/arrangement/XmlArrangementVisitor.java
@@ -4,7 +4,7 @@ import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.XmlElementVisitor;
import com.intellij.psi.codeStyle.arrangement.DefaultArrangementEntry;
-import com.intellij.psi.codeStyle.arrangement.match.ArrangementEntryType;
+import com.intellij.psi.codeStyle.arrangement.std.ArrangementSettingsToken;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
@@ -14,6 +14,9 @@ import org.jetbrains.annotations.Nullable;
import java.util.Collection;
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.EntryType.XML_ATTRIBUTE;
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.EntryType.XML_TAG;
+
/**
* @author Eugene.Kudelevsky
*/
@@ -41,7 +44,7 @@ public class XmlArrangementVisitor extends XmlElementVisitor {
@Override
public void visitXmlTag(XmlTag tag) {
final XmlElementArrangementEntry entry = createNewEntry(
- tag.getTextRange(), ArrangementEntryType.XML_TAG, null, true);
+ tag.getTextRange(), XML_TAG, null, true);
processEntry(entry, tag);
}
@@ -49,7 +52,7 @@ public class XmlArrangementVisitor extends XmlElementVisitor {
public void visitXmlAttribute(XmlAttribute attribute) {
final String name = attribute.isNamespaceDeclaration() ? "" : attribute.getName();
final XmlElementArrangementEntry entry = createNewEntry(
- attribute.getTextRange(), ArrangementEntryType.XML_ATTRIBUTE, name, true);
+ attribute.getTextRange(), XML_ATTRIBUTE, name, true);
processEntry(entry, null);
}
@@ -68,7 +71,7 @@ public class XmlArrangementVisitor extends XmlElementVisitor {
@Nullable
private XmlElementArrangementEntry createNewEntry(@NotNull TextRange range,
- @NotNull ArrangementEntryType type,
+ @NotNull ArrangementSettingsToken type,
@Nullable String name,
boolean canBeMatched) {
if (!isWithinBounds(range)) {
@@ -100,4 +103,6 @@ public class XmlArrangementVisitor extends XmlElementVisitor {
}
return false;
}
+
+
}
diff --git a/xml/impl/src/com/intellij/xml/arrangement/XmlElementArrangementEntry.java b/xml/impl/src/com/intellij/xml/arrangement/XmlElementArrangementEntry.java
index e315a79fbd8a..164465d4b0ae 100644
--- a/xml/impl/src/com/intellij/xml/arrangement/XmlElementArrangementEntry.java
+++ b/xml/impl/src/com/intellij/xml/arrangement/XmlElementArrangementEntry.java
@@ -5,7 +5,7 @@ import com.intellij.psi.codeStyle.arrangement.ArrangementEntry;
import com.intellij.psi.codeStyle.arrangement.DefaultArrangementEntry;
import com.intellij.psi.codeStyle.arrangement.NameAwareArrangementEntry;
import com.intellij.psi.codeStyle.arrangement.TypeAwareArrangementEntry;
-import com.intellij.psi.codeStyle.arrangement.match.ArrangementEntryType;
+import com.intellij.psi.codeStyle.arrangement.std.ArrangementSettingsToken;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -18,14 +18,15 @@ import java.util.Set;
public class XmlElementArrangementEntry extends DefaultArrangementEntry
implements TypeAwareArrangementEntry, NameAwareArrangementEntry {
- private final ArrangementEntryType myType;
- private final String myName;
+ private final ArrangementSettingsToken myType;
+ private final String myName;
public XmlElementArrangementEntry(@Nullable ArrangementEntry parent,
@NotNull TextRange range,
- @NotNull ArrangementEntryType type,
+ @NotNull ArrangementSettingsToken type,
@Nullable String name,
- boolean canBeMatched) {
+ boolean canBeMatched)
+ {
super(parent, range.getStartOffset(), range.getEndOffset(), canBeMatched);
myName = name;
myType = type;
@@ -39,12 +40,7 @@ public class XmlElementArrangementEntry extends DefaultArrangementEntry
@NotNull
@Override
- public Set<ArrangementEntryType> getTypes() {
+ public Set<ArrangementSettingsToken> getTypes() {
return Collections.singleton(myType);
}
-
- @NotNull
- public ArrangementEntryType getType() {
- return myType;
- }
}
diff --git a/xml/impl/src/com/intellij/xml/arrangement/XmlRearranger.java b/xml/impl/src/com/intellij/xml/arrangement/XmlRearranger.java
index a13db532b501..c167236ae7d8 100644
--- a/xml/impl/src/com/intellij/xml/arrangement/XmlRearranger.java
+++ b/xml/impl/src/com/intellij/xml/arrangement/XmlRearranger.java
@@ -7,69 +7,36 @@ import com.intellij.psi.PsiElement;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.arrangement.ArrangementSettings;
import com.intellij.psi.codeStyle.arrangement.Rearranger;
-import com.intellij.psi.codeStyle.arrangement.StdArrangementSettings;
import com.intellij.psi.codeStyle.arrangement.group.ArrangementGroupingRule;
-import com.intellij.psi.codeStyle.arrangement.group.ArrangementGroupingType;
-import com.intellij.psi.codeStyle.arrangement.match.ArrangementEntryType;
-import com.intellij.psi.codeStyle.arrangement.match.ArrangementModifier;
+import com.intellij.psi.codeStyle.arrangement.match.ArrangementEntryMatcher;
import com.intellij.psi.codeStyle.arrangement.match.StdArrangementMatchRule;
import com.intellij.psi.codeStyle.arrangement.model.ArrangementMatchCondition;
-import com.intellij.psi.codeStyle.arrangement.order.ArrangementEntryOrderType;
-import com.intellij.psi.codeStyle.arrangement.settings.ArrangementStandardSettingsAware;
-import com.intellij.psi.codeStyle.arrangement.settings.ArrangementStandardSettingsRepresentationAware;
-import com.intellij.psi.codeStyle.arrangement.settings.DefaultArrangementSettingsRepresentationManager;
-import gnu.trove.TObjectIntHashMap;
+import com.intellij.psi.codeStyle.arrangement.std.*;
+import com.intellij.util.containers.ContainerUtilRt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.EntryType.XML_ATTRIBUTE;
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.EntryType.XML_TAG;
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.General.*;
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Order.BY_NAME;
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Order.KEEP;
+
/**
* @author Eugene.Kudelevsky
*/
public class XmlRearranger
implements Rearranger<XmlElementArrangementEntry>,
- ArrangementStandardSettingsAware,
- ArrangementStandardSettingsRepresentationAware {
-
- private static final Set<ArrangementEntryType> SUPPORTED_TYPES = EnumSet.of(
- ArrangementEntryType.XML_ATTRIBUTE, ArrangementEntryType.XML_TAG);
+ ArrangementStandardSettingsAware {
+ private static final Set<ArrangementSettingsToken> SUPPORTED_TYPES = ContainerUtilRt.newLinkedHashSet(XML_TAG, XML_ATTRIBUTE);
private static final List<StdArrangementMatchRule> DEFAULT_MATCH_RULES = new ArrayList<StdArrangementMatchRule>();
private static final StdArrangementSettings DEFAULT_SETTINGS = new StdArrangementSettings(
Collections.<ArrangementGroupingRule>emptyList(), DEFAULT_MATCH_RULES);
- @NotNull private static final TObjectIntHashMap<Object> WEIGHTS = new TObjectIntHashMap<Object>();
-
- @NotNull
- private static final Comparator<Object> COMPARATOR = new Comparator<Object>() {
- @Override
- public int compare(Object o1, Object o2) {
- if (WEIGHTS.containsKey(o1) && WEIGHTS.containsKey(o2)) {
- return WEIGHTS.get(o1) - WEIGHTS.get(o2);
- }
- else if (WEIGHTS.containsKey(o1) && !WEIGHTS.containsKey(o2)) {
- return -1;
- }
- else if (!WEIGHTS.containsKey(o1) && WEIGHTS.containsKey(o2)) {
- return 1;
- }
- else {
- return o1.hashCode() - o2.hashCode();
- }
- }
- };
-
- static {
- final Object[] ids = {
- ArrangementEntryType.XML_TAG, ArrangementEntryType.XML_ATTRIBUTE
- };
- for (int i = 0; i < ids.length; i++) {
- WEIGHTS.put(ids[i], i);
- }
- }
-
@Nullable
@Override
public StdArrangementSettings getDefaultSettings() {
@@ -77,29 +44,15 @@ public class XmlRearranger
}
@Override
- public boolean isNameFilterSupported() {
- return true;
- }
-
- @Override
- public boolean isEnabled(@NotNull ArrangementEntryType type, @Nullable ArrangementMatchCondition current) {
- return SUPPORTED_TYPES.contains(type);
- }
-
- @Override
- public boolean isEnabled(@NotNull ArrangementModifier modifier, @Nullable ArrangementMatchCondition current) {
- return false;
- }
-
- @Override
- public boolean isEnabled(@NotNull ArrangementGroupingType groupingType, @Nullable ArrangementEntryOrderType orderType) {
- return false;
+ public boolean isEnabled(@NotNull ArrangementSettingsToken token, @Nullable ArrangementMatchCondition current) {
+ return SUPPORTED_TYPES.contains(token) || StdArrangementTokens.Regexp.NAME.equals(token) || StdArrangementTokens.Regexp.XML_NAMESPACE.equals(token) || KEEP.equals(token)
+ || BY_NAME.equals(token) || SUPPORTED_TYPES.contains(token);
}
@NotNull
@Override
- public Collection<Set<?>> getMutexes() {
- return Collections.<Set<?>>singleton(SUPPORTED_TYPES);
+ public Collection<Set<ArrangementSettingsToken>> getMutexes() {
+ return Collections.singleton(SUPPORTED_TYPES);
}
@Nullable
@@ -108,7 +61,8 @@ public class XmlRearranger
@Nullable Document document,
@NotNull Collection<TextRange> ranges,
@NotNull PsiElement element,
- @Nullable ArrangementSettings settings) {
+ @Nullable ArrangementSettings settings)
+ {
final XmlArrangementParseInfo newEntryInfo = new XmlArrangementParseInfo();
element.accept(new XmlArrangementVisitor(newEntryInfo, Collections.singleton(element.getTextRange())));
@@ -140,43 +94,26 @@ public class XmlRearranger
return -1;
}
- @NotNull
- @Override
- public String getDisplayValue(@NotNull ArrangementEntryType type) {
- switch (type) {
- case XML_TAG:
- return "tag";
- case XML_ATTRIBUTE:
- return "attribute";
- default:
- return DefaultArrangementSettingsRepresentationManager.
- INSTANCE.getDisplayValue(type);
- }
- }
-
- @NotNull
- @Override
- public String getDisplayValue(@NotNull ArrangementModifier modifier) {
- return DefaultArrangementSettingsRepresentationManager.INSTANCE.getDisplayValue(modifier);
- }
-
- @NotNull
+ @Nullable
@Override
- public String getDisplayValue(@NotNull ArrangementGroupingType groupingType) {
- return DefaultArrangementSettingsRepresentationManager.INSTANCE.getDisplayValue(groupingType);
+ public List<CompositeArrangementSettingsToken> getSupportedGroupingTokens() {
+ return null;
}
- @NotNull
+ @Nullable
@Override
- public String getDisplayValue(@NotNull ArrangementEntryOrderType orderType) {
- return DefaultArrangementSettingsRepresentationManager.INSTANCE.getDisplayValue(orderType);
+ public List<CompositeArrangementSettingsToken> getSupportedMatchingTokens() {
+ return ContainerUtilRt.newArrayList(
+ new CompositeArrangementSettingsToken(TYPE, SUPPORTED_TYPES),
+ new CompositeArrangementSettingsToken(StdArrangementTokens.Regexp.NAME),
+ new CompositeArrangementSettingsToken(StdArrangementTokens.Regexp.XML_NAMESPACE),
+ new CompositeArrangementSettingsToken(ORDER, KEEP, BY_NAME)
+ );
}
@NotNull
@Override
- public <T> List<T> sort(@NotNull Collection<T> ids) {
- final List<T> result = new ArrayList<T>(ids);
- Collections.sort(result, COMPARATOR);
- return result;
+ public ArrangementEntryMatcher buildMatcher(@NotNull ArrangementMatchCondition condition) throws IllegalArgumentException {
+ throw new IllegalArgumentException("Can't build a matcher for condition " + condition);
}
}
diff --git a/xml/impl/src/com/intellij/xml/impl/schema/XmlElementDescriptorImpl.java b/xml/impl/src/com/intellij/xml/impl/schema/XmlElementDescriptorImpl.java
index 643470597dba..ac00589000d2 100644
--- a/xml/impl/src/com/intellij/xml/impl/schema/XmlElementDescriptorImpl.java
+++ b/xml/impl/src/com/intellij/xml/impl/schema/XmlElementDescriptorImpl.java
@@ -109,10 +109,10 @@ public class XmlElementDescriptorImpl implements XmlElementDescriptor, PsiWritab
public String getNamespace(){
String name = getName();
if (name == null) return XmlUtil.EMPTY_URI;
- final String namespacePrefix = XmlUtil.findPrefixByQualifiedName(name);
final XmlNSDescriptorImpl xmlNSDescriptor = (XmlNSDescriptorImpl)getNSDescriptor();
- if(xmlNSDescriptor == null || myDescriptorTag == null) return XmlUtil.EMPTY_URI;
- return "".equals(namespacePrefix) ?
+ if (xmlNSDescriptor == null || myDescriptorTag == null) return XmlUtil.EMPTY_URI;
+ final String namespacePrefix = XmlUtil.findPrefixByQualifiedName(name);
+ return namespacePrefix.isEmpty() ?
xmlNSDescriptor.getDefaultNamespace() :
myDescriptorTag.getNamespaceByPrefix(namespacePrefix);
}
diff --git a/xml/impl/src/com/intellij/xml/util/HtmlUtil.java b/xml/impl/src/com/intellij/xml/util/HtmlUtil.java
index 91cb2bccdd03..86252c1d22f1 100644
--- a/xml/impl/src/com/intellij/xml/util/HtmlUtil.java
+++ b/xml/impl/src/com/intellij/xml/util/HtmlUtil.java
@@ -308,9 +308,8 @@ public class HtmlUtil {
switch (type) {
case XmlEntitiesInspection.UNKNOWN_TAG:
- LocalInspectionToolWrapper wrapper = (LocalInspectionToolWrapper)profile.getInspectionTool(HtmlUnknownTagInspection.TAG_SHORT_NAME,
- containingFile);
- HtmlUnknownTagInspection unknownTagInspection = wrapper != null ? (HtmlUnknownTagInspection)wrapper.getTool() : null;
+ HtmlUnknownTagInspection unknownTagInspection = (HtmlUnknownTagInspection)profile.getUnwrappedTool(HtmlUnknownTagInspection.TAG_SHORT_NAME,
+ containingFile);
if (unknownTagInspection != null) {
return unknownTagInspection.getAdditionalEntries();
}
diff --git a/xml/impl/src/com/intellij/xml/util/XmlDuplicatedIdInspection.java b/xml/impl/src/com/intellij/xml/util/XmlDuplicatedIdInspection.java
index 19b2012fdd1e..ddee1092680d 100644
--- a/xml/impl/src/com/intellij/xml/util/XmlDuplicatedIdInspection.java
+++ b/xml/impl/src/com/intellij/xml/util/XmlDuplicatedIdInspection.java
@@ -15,28 +15,22 @@
*/
package com.intellij.xml.util;
-import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.daemon.XmlErrorMessages;
-import com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor;
-import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
-import com.intellij.openapi.extensions.Extensions;
+import com.intellij.codeInspection.XmlSuppressableInspectionTool;
import com.intellij.psi.*;
-import com.intellij.psi.html.HtmlTag;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
-import com.intellij.xml.XmlBundle;
-import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
/**
* @author Dmitry Avdeev
*/
-public class XmlDuplicatedIdInspection extends LocalInspectionTool {
+public class XmlDuplicatedIdInspection extends XmlSuppressableInspectionTool {
@NotNull
@Override
@@ -64,70 +58,15 @@ public class XmlDuplicatedIdInspection extends LocalInspectionTool {
final XmlTag tag = (XmlTag)parent.getParent();
if (tag == null) return;
- if (refHolder.isValidatable(tag.getParent()) && refHolder.isDuplicateIdAttributeValue(value)) {
- holder.registerProblem(value, XmlErrorMessages.message("duplicate.id.reference"), ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
- }
-
- String idRef = XmlHighlightVisitor.getUnquotedValue(value, tag);
-
- if (tag instanceof HtmlTag) {
- idRef = idRef.toLowerCase();
- }
-
- if (XmlUtil.isSimpleXmlAttributeValue(idRef, value) && refHolder.isIdReferenceValue(value)) {
- boolean hasIdDeclaration = refHolder.hasIdDeclaration(idRef);
- if (!hasIdDeclaration && tag instanceof HtmlTag) {
- hasIdDeclaration = refHolder.hasIdDeclaration(value.getValue());
- }
-
- if (!hasIdDeclaration) {
- for(XmlIdContributor contributor: Extensions.getExtensions(XmlIdContributor.EP_NAME)) {
- if (contributor.suppressExistingIdValidation((XmlFile)file)) {
- return;
- }
- }
-
- final FileViewProvider viewProvider = tag.getContainingFile().getViewProvider();
- if (viewProvider instanceof MultiplePsiFilesPerDocumentFileViewProvider) {
- holder.registerProblem(value, XmlErrorMessages.message("invalid.id.reference"), ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
- new XmlDeclareIdInCommentAction(idRef));
-
- }
- else {
- holder.registerProblem(value, XmlErrorMessages.message("invalid.id.reference"), ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
- }
- }
- }
+ checkValue(value, (XmlFile)file, refHolder, tag, holder);
}
};
}
- public boolean runForWholeFile() {
- return false;
- }
-
- @NotNull
- public HighlightDisplayLevel getDefaultLevel() {
- return HighlightDisplayLevel.ERROR;
- }
-
- public boolean isEnabledByDefault() {
- return true;
- }
-
- @NotNull
- public String getGroupDisplayName() {
- return XmlBundle.message("xml.inspections.group.name");
- }
-
- @NotNull
- public String getDisplayName() {
- return XmlBundle.message("xml.inspections.duplicate.id");
- }
-
- @NotNull
- @NonNls
- public String getShortName() {
- return "XmlDuplicatedId";
+ protected void checkValue(XmlAttributeValue value, XmlFile file, XmlRefCountHolder refHolder, XmlTag tag, ProblemsHolder holder) {
+ if (refHolder.isValidatable(tag.getParent()) && refHolder.isDuplicateIdAttributeValue(value)) {
+ holder.registerProblem(value, XmlErrorMessages.message("duplicate.id.reference"), ProblemHighlightType.GENERIC_ERROR,
+ ElementManipulators.getValueTextRange(value));
+ }
}
}
diff --git a/xml/impl/src/com/intellij/xml/util/XmlInvalidIdInspection.java b/xml/impl/src/com/intellij/xml/util/XmlInvalidIdInspection.java
new file mode 100644
index 000000000000..afe28eda4b4d
--- /dev/null
+++ b/xml/impl/src/com/intellij/xml/util/XmlInvalidIdInspection.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.xml.util;
+
+import com.intellij.codeInsight.daemon.XmlErrorMessages;
+import com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor;
+import com.intellij.codeInspection.ProblemHighlightType;
+import com.intellij.codeInspection.ProblemsHolder;
+import com.intellij.openapi.extensions.Extensions;
+import com.intellij.psi.FileViewProvider;
+import com.intellij.psi.MultiplePsiFilesPerDocumentFileViewProvider;
+import com.intellij.psi.html.HtmlTag;
+import com.intellij.psi.xml.XmlAttributeValue;
+import com.intellij.psi.xml.XmlFile;
+import com.intellij.psi.xml.XmlTag;
+
+/**
+ * @author Dmitry Avdeev
+ */
+public class XmlInvalidIdInspection extends XmlDuplicatedIdInspection {
+
+ protected void checkValue(XmlAttributeValue value, XmlFile file, XmlRefCountHolder refHolder, XmlTag tag, ProblemsHolder holder) {
+
+ String idRef = XmlHighlightVisitor.getUnquotedValue(value, tag);
+
+ if (tag instanceof HtmlTag) {
+ idRef = idRef.toLowerCase();
+ }
+
+ if (XmlUtil.isSimpleXmlAttributeValue(idRef, value) && refHolder.isIdReferenceValue(value)) {
+ boolean hasIdDeclaration = refHolder.hasIdDeclaration(idRef);
+ if (!hasIdDeclaration && tag instanceof HtmlTag) {
+ hasIdDeclaration = refHolder.hasIdDeclaration(value.getValue());
+ }
+
+ if (!hasIdDeclaration) {
+ for(XmlIdContributor contributor: Extensions.getExtensions(XmlIdContributor.EP_NAME)) {
+ if (contributor.suppressExistingIdValidation(file)) {
+ return;
+ }
+ }
+
+ final FileViewProvider viewProvider = tag.getContainingFile().getViewProvider();
+ if (viewProvider instanceof MultiplePsiFilesPerDocumentFileViewProvider) {
+ holder.registerProblem(value, XmlErrorMessages.message("invalid.id.reference"), ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
+ new XmlDeclareIdInCommentAction(idRef));
+
+ }
+ else {
+ holder.registerProblem(value, XmlErrorMessages.message("invalid.id.reference"), ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
+ }
+ }
+ }
+ }
+}
diff --git a/xml/impl/src/com/intellij/xml/util/XmlReferenceContributor.java b/xml/impl/src/com/intellij/xml/util/XmlReferenceContributor.java
index 6b68974f4ecc..21d6abcca803 100644
--- a/xml/impl/src/com/intellij/xml/util/XmlReferenceContributor.java
+++ b/xml/impl/src/com/intellij/xml/util/XmlReferenceContributor.java
@@ -4,7 +4,6 @@ import com.intellij.codeInsight.daemon.impl.analysis.encoding.XmlEncodingReferen
import com.intellij.html.impl.providers.MicrodataReferenceProvider;
import com.intellij.html.impl.util.MicrodataUtil;
import com.intellij.patterns.PlatformPatterns;
-import com.intellij.patterns.XmlPatterns;
import com.intellij.psi.PsiReferenceContributor;
import com.intellij.psi.PsiReferenceRegistrar;
import com.intellij.psi.filters.*;
@@ -16,7 +15,6 @@ import com.intellij.psi.impl.source.resolve.reference.impl.providers.SchemaRefer
import com.intellij.psi.impl.source.resolve.reference.impl.providers.URIReferenceProvider;
import com.intellij.psi.xml.*;
-import static com.intellij.patterns.StandardPatterns.string;
import static com.intellij.patterns.XmlPatterns.*;
/**
@@ -82,7 +80,7 @@ public class XmlReferenceContributor extends PsiReferenceContributor {
registrar.registerReferenceProvider(
xmlAttributeValue().withLocalName("schemaLocation","namespace").
withSuperParent(2,
- xmlTag().withNamespace(XmlUtil.SCHEMA_URIS).withLocalName(string().oneOf("import", "include","redefine"))),
+ xmlTag().withNamespace(XmlUtil.SCHEMA_URIS).withLocalName("import", "include","redefine")),
uriProvider);
XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, null, URIReferenceProvider.ELEMENT_FILTER, true, uriProvider);
@@ -90,6 +88,6 @@ public class XmlReferenceContributor extends PsiReferenceContributor {
XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, new String[] {"encoding"}, new ScopeFilter(new ParentElementFilter(new ClassFilter(XmlProcessingInstruction.class))), true,
new XmlEncodingReferenceProvider());
- registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue(), new XmlPrefixReferenceProvider());
+ registrar.registerReferenceProvider(xmlAttributeValue(), new XmlPrefixReferenceProvider());
}
}
diff --git a/xml/impl/src/com/intellij/xml/util/XmlUtil.java b/xml/impl/src/com/intellij/xml/util/XmlUtil.java
index e9c8abd6c2ba..f18bf30f993b 100644
--- a/xml/impl/src/com/intellij/xml/util/XmlUtil.java
+++ b/xml/impl/src/com/intellij/xml/util/XmlUtil.java
@@ -197,15 +197,15 @@ public class XmlUtil {
}
@Nullable
- public static String findNamespacePrefixByURI(XmlFile file, @NonNls String uri) {
+ public static String findNamespacePrefixByURI(XmlFile file, @NotNull @NonNls String uri) {
final XmlTag tag = file.getRootTag();
if (tag == null) return null;
for (XmlAttribute attribute : tag.getAttributes()) {
- if (attribute.getName().startsWith("xmlns:") && attribute.getValue().equals(uri)) {
+ if (attribute.getName().startsWith("xmlns:") && uri.equals(attribute.getValue())) {
return attribute.getName().substring("xmlns:".length());
}
- if ("xmlns".equals(attribute.getName()) && attribute.getValue().equals(uri)) return "";
+ if ("xmlns".equals(attribute.getName()) && uri.equals(attribute.getValue())) return "";
}
return null;
@@ -1398,6 +1398,7 @@ public class XmlUtil {
return contextTag.getNamespaceByPrefix(prefix);
}
+ @NotNull
public static String findPrefixByQualifiedName(@NotNull String name) {
final int prefixEnd = name.indexOf(':');
if (prefixEnd > 0) {
diff --git a/xml/openapi/src/com/intellij/patterns/XmlAttributeValuePattern.java b/xml/openapi/src/com/intellij/patterns/XmlAttributeValuePattern.java
index 459b9d36c6e8..8cfd471e936d 100644
--- a/xml/openapi/src/com/intellij/patterns/XmlAttributeValuePattern.java
+++ b/xml/openapi/src/com/intellij/patterns/XmlAttributeValuePattern.java
@@ -41,6 +41,10 @@ public class XmlAttributeValuePattern extends XmlElementPattern<XmlAttributeValu
}
public XmlAttributeValuePattern withLocalName(@NonNls String... names) {
+ if (names.length == 1) {
+ return withLocalName(StandardPatterns.string().equalTo(names[0]));
+ }
+
return withLocalName(StandardPatterns.string().oneOf(names));
}
diff --git a/xml/openapi/src/com/intellij/patterns/XmlNamedElementPattern.java b/xml/openapi/src/com/intellij/patterns/XmlNamedElementPattern.java
index c0d366b2ccda..2bc01880db02 100644
--- a/xml/openapi/src/com/intellij/patterns/XmlNamedElementPattern.java
+++ b/xml/openapi/src/com/intellij/patterns/XmlNamedElementPattern.java
@@ -40,6 +40,10 @@ public abstract class XmlNamedElementPattern<T extends XmlElement & PsiNamedElem
return withLocalName(StandardPatterns.string().equalTo(localName));
}
+ public Self withLocalName(@NonNls String... localNames) {
+ return withLocalName(StandardPatterns.string().oneOf(localNames));
+ }
+
public Self withLocalName(final ElementPattern<String> localName) {
return with(new PsiNamePatternCondition<T>("withLocalName", localName) {
public String getPropertyValue(@NotNull final Object o) {
@@ -48,8 +52,12 @@ public abstract class XmlNamedElementPattern<T extends XmlElement & PsiNamedElem
});
}
+ public Self withNamespace(@NonNls final String namespace) {
+ return withNamespace(StandardPatterns.string().equalTo(namespace));
+ }
+
public Self withNamespace(@NonNls final String... namespaces) {
- return withNamespace(PlatformPatterns.string().oneOf(namespaces));
+ return withNamespace(StandardPatterns.string().oneOf(namespaces));
}
public Self withNamespace(final ElementPattern<String> namespace) {
diff --git a/xml/openapi/src/com/intellij/psi/xml/XmlAttribute.java b/xml/openapi/src/com/intellij/psi/xml/XmlAttribute.java
index 0ba6a7ef2719..3c49760b03f7 100644
--- a/xml/openapi/src/com/intellij/psi/xml/XmlAttribute.java
+++ b/xml/openapi/src/com/intellij/psi/xml/XmlAttribute.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,11 +42,13 @@ public interface XmlAttribute extends XmlElement, PsiNamedElement {
/**
* @return text inside XML attribute with quotes stripped off
*/
+ @Nullable
String getValue();
/**
* @return text inside XML attribute with quotes stripped off and XML char entities replaced with corresponding characters
*/
+ @Nullable
String getDisplayValue();
/**
@@ -73,9 +75,6 @@ public interface XmlAttribute extends XmlElement, PsiNamedElement {
@Nullable XmlAttributeDescriptor getDescriptor();
- // Tree functions
-
- // TODO: remove this. For tree functions XmlChildRole.XXX_FINDER should be used.
// In this case function is also used to get references from attribute value
@Nullable
XmlAttributeValue getValueElement();
diff --git a/xml/openapi/src/com/intellij/psi/xml/XmlTagChild.java b/xml/openapi/src/com/intellij/psi/xml/XmlTagChild.java
index 5e0129ab5df5..d1a322e39cb4 100644
--- a/xml/openapi/src/com/intellij/psi/xml/XmlTagChild.java
+++ b/xml/openapi/src/com/intellij/psi/xml/XmlTagChild.java
@@ -15,7 +15,6 @@
*/
package com.intellij.psi.xml;
-import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface XmlTagChild extends XmlElement{
diff --git a/xml/openapi/src/com/intellij/xml/breadcrumbs/BreadcrumbsComponent.java b/xml/openapi/src/com/intellij/xml/breadcrumbs/BreadcrumbsComponent.java
index 9072862fd589..9e3b5ae2107c 100644
--- a/xml/openapi/src/com/intellij/xml/breadcrumbs/BreadcrumbsComponent.java
+++ b/xml/openapi/src/com/intellij/xml/breadcrumbs/BreadcrumbsComponent.java
@@ -21,6 +21,7 @@ import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
+import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -41,7 +42,7 @@ public class BreadcrumbsComponent<T extends BreadcrumbsItem> extends JComponent
private static final Logger LOG = Logger.getInstance("#com.intellij.xml.breadcrumbs.BreadcrumbsComponent");
private static final Painter DEFAULT_PAINTER = new DefaultPainter(new ButtonSettings());
- private List<BreadcrumbsItemListener<T>> myListeners = new ArrayList<BreadcrumbsItemListener<T>>();
+ private List<BreadcrumbsItemListener<T>> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private Crumb myHovered;
private PagedImage myBuffer;
private List<Crumb> myCrumbs = new ArrayList<Crumb>();
@@ -212,9 +213,8 @@ public class BreadcrumbsComponent<T extends BreadcrumbsItem> extends JComponent
@SuppressWarnings({"ForLoopReplaceableByForEach"})
private void fireItemSelected(@Nullable final T item, final int modifiers) {
if (item != null) {
- final BreadcrumbsItemListener[] listeners = myListeners.toArray(new BreadcrumbsItemListener[myListeners.size()]);
- for (int i = 0; i < listeners.length; i++) {
- listeners[i].itemSelected(item, modifiers);
+ for (BreadcrumbsItemListener listener : myListeners) {
+ listener.itemSelected(item, modifiers);
}
}
}
diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/RelaxNGReferenceContributor.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/RelaxNGReferenceContributor.java
index 08b281c95183..216271f46494 100644
--- a/xml/relaxng/src/org/intellij/plugins/relaxNG/RelaxNGReferenceContributor.java
+++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/RelaxNGReferenceContributor.java
@@ -1,29 +1,26 @@
package org.intellij.plugins.relaxNG;
-import com.intellij.patterns.StringPattern;
import com.intellij.patterns.XmlNamedElementPattern;
import com.intellij.psi.PsiReferenceContributor;
import com.intellij.psi.PsiReferenceRegistrar;
import com.intellij.psi.filters.position.PatternFilter;
+import com.intellij.psi.xml.XmlTag;
import com.intellij.xml.util.XmlUtil;
import org.intellij.plugins.relaxNG.references.PrefixReferenceProvider;
import static com.intellij.patterns.StandardPatterns.string;
-import static com.intellij.patterns.XmlPatterns.xmlAttribute;
-import static com.intellij.patterns.XmlPatterns.xmlAttributeValue;
-import static com.intellij.patterns.XmlPatterns.xmlTag;
+import static com.intellij.patterns.XmlPatterns.*;
/**
* @author peter
*/
public class RelaxNGReferenceContributor extends PsiReferenceContributor {
- private static final XmlNamedElementPattern RNG_TAG_PATTERN = xmlTag().withNamespace(string().equalTo(ApplicationLoader.RNG_NAMESPACE));
+ private static final XmlNamedElementPattern RNG_TAG_PATTERN = xmlTag().withNamespace(ApplicationLoader.RNG_NAMESPACE);
private static final XmlNamedElementPattern.XmlAttributePattern NAME_ATTR_PATTERN = xmlAttribute("name");
- private static final StringPattern ELEMENT_OR_ATTRIBUTE_PATTERN = string().oneOf("element", "attribute");
private static final XmlNamedElementPattern.XmlAttributePattern NAME_PATTERN = NAME_ATTR_PATTERN.withParent(
- RNG_TAG_PATTERN.withLocalName(ELEMENT_OR_ATTRIBUTE_PATTERN));
+ RNG_TAG_PATTERN.withLocalName("element", "attribute"));
@Override
public void registerReferenceProviders(PsiReferenceRegistrar registrar) {
diff --git a/xml/tests/src/com/intellij/codeInsight/completion/XmlCompletionTest.java b/xml/tests/src/com/intellij/codeInsight/completion/XmlCompletionTest.java
index 999dd037987c..cf2bd9a5bbfe 100644
--- a/xml/tests/src/com/intellij/codeInsight/completion/XmlCompletionTest.java
+++ b/xml/tests/src/com/intellij/codeInsight/completion/XmlCompletionTest.java
@@ -168,19 +168,15 @@ public class XmlCompletionTest extends LightCodeInsightFixtureTestCase {
}
public void testAttributesTemplateFinishWithSpace() throws Throwable {
- ((TemplateManagerImpl)TemplateManager.getInstance(getProject())).setTemplateTesting(true);
- try {
- configureByFile(getTestName(false) + ".xml");
- type('b');
- type('e');
- type('a');
- type('n');
- type(' ');
- checkResultByFile(getTestName(false) + "_after.xml");
- }
- finally {
- ((TemplateManagerImpl)TemplateManager.getInstance(getProject())).setTemplateTesting(false);
- }
+ TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable());
+
+ configureByFile(getTestName(false) + ".xml");
+ type('b');
+ type('e');
+ type('a');
+ type('n');
+ type(' ');
+ checkResultByFile(getTestName(false) + "_after.xml");
}
private void configureByFile(String s) {
@@ -189,17 +185,13 @@ public class XmlCompletionTest extends LightCodeInsightFixtureTestCase {
}
public void testNoAttributesTemplateFinishWithSpace() throws Throwable {
- ((TemplateManagerImpl)TemplateManager.getInstance(getProject())).setTemplateTesting(true);
- try {
- configureByFile(getTestName(false) + ".xml");
- type('d');
- type('e');
- type(' ');
- checkResultByFile(getTestName(false) + "_after.xml");
- }
- finally {
- ((TemplateManagerImpl)TemplateManager.getInstance(getProject())).setTemplateTesting(false);
- }
+ TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable());
+
+ configureByFile(getTestName(false) + ".xml");
+ type('d');
+ type('e');
+ type(' ');
+ checkResultByFile(getTestName(false) + "_after.xml");
}
private void type(char c) {
diff --git a/xml/tests/src/com/intellij/codeInsight/completion/XmlSmartEnterTest.java b/xml/tests/src/com/intellij/codeInsight/completion/XmlSmartEnterTest.java
index 0ec36a34e2d4..9d9b056b1e5f 100644
--- a/xml/tests/src/com/intellij/codeInsight/completion/XmlSmartEnterTest.java
+++ b/xml/tests/src/com/intellij/codeInsight/completion/XmlSmartEnterTest.java
@@ -84,6 +84,11 @@ public class XmlSmartEnterTest extends LightCodeInsightTestCase {
checkResultByFile("", BASE_PATH + "/" + "CompleteMissingTag_after_5.xml", true);
}
+ public void testSmartCloseTag2() throws Exception {
+ _doTest("idea103417_1.xml", "idea103417_1_after.xml");
+ _doTest("idea103417_2.xml", "idea103417_2_after.xml");
+ }
+
private void _doTestCompletion(final String name, final String after_name) throws Exception {
configureByFile(BASE_PATH + "/" + name);
performCompletionAction();
diff --git a/xml/tests/src/com/intellij/codeInsight/daemon/XmlHighlightingTest.java b/xml/tests/src/com/intellij/codeInsight/daemon/XmlHighlightingTest.java
index fa3797b31a06..629a7b32ea1d 100644
--- a/xml/tests/src/com/intellij/codeInsight/daemon/XmlHighlightingTest.java
+++ b/xml/tests/src/com/intellij/codeInsight/daemon/XmlHighlightingTest.java
@@ -953,6 +953,7 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase {
return new LocalInspectionTool[]{
new RequiredAttributesInspection(),
new XmlDuplicatedIdInspection(),
+ new XmlInvalidIdInspection(),
new CheckDtdReferencesInspection(),
new XmlUnboundNsPrefixInspection(),
new XmlPathReferenceInspection()
diff --git a/xml/tests/src/com/intellij/codeInsight/daemon/quickFix/ExtractExternalResourceLinksTest.java b/xml/tests/src/com/intellij/codeInsight/daemon/quickFix/ExtractExternalResourceLinksTest.java
index 85b1069a8fd5..5e2852142e09 100644
--- a/xml/tests/src/com/intellij/codeInsight/daemon/quickFix/ExtractExternalResourceLinksTest.java
+++ b/xml/tests/src/com/intellij/codeInsight/daemon/quickFix/ExtractExternalResourceLinksTest.java
@@ -1,15 +1,17 @@
package com.intellij.codeInsight.daemon.quickFix;
-import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.codeInsight.daemon.impl.quickfix.FetchExtResourceAction;
import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.testFramework.PlatformTestUtil;
+import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
-public class ExtractExternalResourceLinksTest extends CodeInsightTestCase {
+public class ExtractExternalResourceLinksTest extends LightCodeInsightTestCase {
protected static String getBasePath() {
return "/quickFix/fetchExternalResources";
@@ -18,13 +20,11 @@ public class ExtractExternalResourceLinksTest extends CodeInsightTestCase {
public void testExtractionOfEmbeddedFiles() throws Exception {
doExtractionOfEmbeddedFiles(
"1.dtd",
- new String[] {"xhtml-lat1.ent", "xhtml-symbol.ent", "xhtml-special.ent"}
- );
+ "xhtml-lat1.ent", "xhtml-symbol.ent", "xhtml-special.ent");
doExtractionOfEmbeddedFiles(
"1.xsd",
- new String[] {"j2ee_1_4.xsd", "jsp_2_0.xsd"}
- );
+ "j2ee_1_4.xsd", "jsp_2_0.xsd");
doExtractionOfEmbeddedFiles(
new String[] { "2.dtd", "2.mod" },
@@ -43,36 +43,36 @@ public class ExtractExternalResourceLinksTest extends CodeInsightTestCase {
doExtractionOfEmbeddedFiles(
"3.xsd",
- new String[] {"j2ee_1_4.xsd", "jsp_2_0.xsd"}
- );
+ "j2ee_1_4.xsd", "jsp_2_0.xsd");
doExtractionOfEmbeddedFiles(
"4.xml",
- new String[] {
- "http://www.springframework.org/schema/beans/spring-beans.xsd",
- "http://www.springframework.org/schema/aop/spring-aop.xsd",
- "http://www.springframework.org/schema/tx/spring-tx.xsd"
- }
- );
+ "http://www.springframework.org/schema/beans/spring-beans.xsd",
+ "http://www.springframework.org/schema/aop/spring-aop.xsd",
+ "http://www.springframework.org/schema/tx/spring-tx.xsd");
doExtractionOfEmbeddedFiles(
"5.xml",
- new String[] {
- "http://geronimo.apache.org/xml/ns/geronimo-naming-1.1.xsd",
- "http://geronimo.apache.org/xml/ns/geronimo-security-1.1.xsd",
- "http://geronimo.apache.org/xml/ns/geronimo-module-1.1.xsd"
- }
- );
+ "geronimo-naming-1.1.xsd",
+ "geronimo-security-1.1.xsd",
+ "geronimo-module-1.1.xsd");
+ }
+
+ public void testSeamImport() throws Exception {
doExtractionOfEmbeddedFiles(
"6.xml",
- new String[] {
- "http://jboss.com/products/seam/components-1.2.xsd"
- }
- );
+ "http://jboss.com/products/seam/components-1.2.xsd");
+
+ }
+
+ public void testBPMN() throws Exception {
+ doExtractionOfEmbeddedFiles("BPMN20.xsd",
+ "BPMNDI.xsd", "Semantic.xsd");
+
}
- private void doExtractionOfEmbeddedFiles(String shortFileName,String[] expectedFileNames) throws Exception {
+ private void doExtractionOfEmbeddedFiles(String shortFileName,String... expectedFileNames) throws Exception {
doExtractionOfEmbeddedFiles(new String[] {shortFileName}, new String[][] {expectedFileNames} );
}
@@ -85,15 +85,15 @@ public class ExtractExternalResourceLinksTest extends CodeInsightTestCase {
int fileIndex = 0;
for(String[] expectedFileNameArray:expectedFileNames) {
- List<String> strings = FetchExtResourceAction.extractEmbeddedFileReferences(
- files.get(fileIndex), fileIndex != 0? files.get(0): null, getPsiManager()
+ Set<String> strings = FetchExtResourceAction.extractEmbeddedFileReferences(
+ files.get(fileIndex), fileIndex != 0 ? files.get(0) : null, getPsiManager()
);
- assertEquals(expectedFileNameArray.length,strings.size());
+ assertEquals(expectedFileNameArray.length, strings.size());
int index = 0;
for (final String string : strings) {
- assertEquals(string, expectedFileNameArray[index]);
+ assertEquals(expectedFileNameArray[index], string);
++index;
}
@@ -101,6 +101,7 @@ public class ExtractExternalResourceLinksTest extends CodeInsightTestCase {
}
}
+ @NotNull
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/xml/tests/testData/";
diff --git a/xml/tests/src/com/intellij/codeInsight/template/XmlLiveTemplateTest.groovy b/xml/tests/src/com/intellij/codeInsight/template/XmlLiveTemplateTest.groovy
index 6ae391ddbf7b..c928a92a7e57 100644
--- a/xml/tests/src/com/intellij/codeInsight/template/XmlLiveTemplateTest.groovy
+++ b/xml/tests/src/com/intellij/codeInsight/template/XmlLiveTemplateTest.groovy
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.intellij.codeInsight.template
-import com.intellij.codeInsight.CodeInsightSettings
+
import com.intellij.codeInsight.template.impl.ConstantNode
import com.intellij.codeInsight.template.impl.EmptyNode
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
@@ -32,13 +32,11 @@ public class XmlLiveTemplateTest extends LightCodeInsightFixtureTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
- ((TemplateManagerImpl)TemplateManager.getInstance(getProject())).setTemplateTesting(true);
+ TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable());
}
@Override
protected void tearDown() throws Exception {
- CodeInsightSettings.instance.COMPLETION_CASE_SENSITIVE = CodeInsightSettings.FIRST_LETTER
- ((TemplateManagerImpl)TemplateManager.getInstance(getProject())).setTemplateTesting(false);
if (state != null) {
state.gotoEnd();
}
diff --git a/xml/impl/src/com/intellij/codeInspection/htmlInspections/XmlInspectionToolProvider.java b/xml/tests/src/com/intellij/codeInspection/htmlInspections/XmlInspectionToolProvider.java
index 287591f79901..287591f79901 100644
--- a/xml/impl/src/com/intellij/codeInspection/htmlInspections/XmlInspectionToolProvider.java
+++ b/xml/tests/src/com/intellij/codeInspection/htmlInspections/XmlInspectionToolProvider.java
diff --git a/xml/tests/src/com/intellij/xml/arrangement/XmlRearrangerTest.groovy b/xml/tests/src/com/intellij/xml/arrangement/XmlRearrangerTest.groovy
index 0f252fa0ab24..15c3649478c0 100644
--- a/xml/tests/src/com/intellij/xml/arrangement/XmlRearrangerTest.groovy
+++ b/xml/tests/src/com/intellij/xml/arrangement/XmlRearrangerTest.groovy
@@ -3,7 +3,8 @@ import com.intellij.ide.highlighter.XmlFileType
import com.intellij.lang.xml.XMLLanguage
import com.intellij.psi.codeStyle.arrangement.AbstractRearrangerTest
-import static com.intellij.psi.codeStyle.arrangement.order.ArrangementEntryOrderType.BY_NAME
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Order.BY_NAME
+
/**
* @author Eugene.Kudelevsky
*/
@@ -17,7 +18,7 @@ class XmlRearrangerTest extends AbstractRearrangerTest {
doTest(
initial: '''<root xmlns:ns="http://ns.com" attr2="value2" attr1="value1" attr3="value3"/>''',
expected: '''<root xmlns:ns="http://ns.com" attr1="value1" attr2="value2" attr3="value3"/>''',
- rules: [rule(BY_NAME, ".*")]
+ rules: [ruleWithOrder(BY_NAME, nameRule(".*"))]
)
}
@@ -25,7 +26,7 @@ class XmlRearrangerTest extends AbstractRearrangerTest {
doTest(
initial: '''<root attr3="value3" attr2="value2" attr1="value1" xmlns:ns="http://ns.com"/>''',
expected: '''<root xmlns:ns="http://ns.com" attr1="value1" attr2="value2" attr3="value3"/>''',
- rules: [rule(BY_NAME, ".*")]
+ rules: [ruleWithOrder(BY_NAME, nameRule(".*"))]
)
}
@@ -47,7 +48,7 @@ class XmlRearrangerTest extends AbstractRearrangerTest {
</tag1>
</root>
''',
- rules: [rule(BY_NAME, ".*")]
+ rules: [ruleWithOrder(BY_NAME, nameRule(".*"))]
)
}
}
diff --git a/xml/tests/testData/mover/tag5_afterDown.xml b/xml/tests/testData/mover/tag5_afterDown.xml
new file mode 100644
index 000000000000..7a0f990e2377
--- /dev/null
+++ b/xml/tests/testData/mover/tag5_afterDown.xml
@@ -0,0 +1,11 @@
+<orcontainer>
+ <empty1 attr1="N0"/>
+ <empty1 attr1="N1"
+ attr2="some">
+ <sub-empty/>
+ </empty1>
+ <empty1 attr1="N2"/>
+ <empty1 attr1="N3"
+ attr2="some"/>
+</orcontainer>
+<selection><empty1 attr1="N4"/></selection>
diff --git a/xml/tests/testData/quickFix/fetchExternalResources/BPMN20.xsd b/xml/tests/testData/quickFix/fetchExternalResources/BPMN20.xsd
new file mode 100644
index 000000000000..5fe48e8566ff
--- /dev/null
+++ b/xml/tests/testData/quickFix/fetchExternalResources/BPMN20.xsd
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsd:schema elementFormDefault="qualified" attributeFormDefault="unqualified"
+ xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
+ targetNamespace="http://www.omg.org/spec/BPMN/20100524/MODEL">
+
+ <xsd:import namespace="http://www.omg.org/spec/BPMN/20100524/DI" schemaLocation="BPMNDI.xsd"/>
+ <xsd:include schemaLocation="Semantic.xsd"/>
+
+ <xsd:element name="definitions" type="tDefinitions"/>
+ <xsd:complexType name="tDefinitions">
+ <xsd:sequence>
+ <xsd:element ref="import" minOccurs="0" maxOccurs="unbounded"/>
+ <xsd:element ref="extension" minOccurs="0" maxOccurs="unbounded"/>
+ <xsd:element ref="rootElement" minOccurs="0" maxOccurs="unbounded"/>
+ <xsd:element ref="bpmndi:BPMNDiagram" minOccurs="0" maxOccurs="unbounded"/>
+ <xsd:element ref="relationship" minOccurs="0" maxOccurs="unbounded"/>
+ </xsd:sequence>
+ <xsd:attribute name="id" type="xsd:ID" use="optional"/>
+ <xsd:attribute name="name" type="xsd:string"/>
+ <xsd:attribute name="targetNamespace" type="xsd:anyURI" use="required"/>
+ <xsd:attribute name="expressionLanguage" type="xsd:anyURI" use="optional" default="http://www.w3.org/1999/XPath"/>
+ <xsd:attribute name="typeLanguage" type="xsd:anyURI" use="optional" default="http://www.w3.org/2001/XMLSchema"/>
+ <xsd:attribute name="exporter" type="xsd:string"/>
+ <xsd:attribute name="exporterVersion" type="xsd:string"/>
+ <xsd:anyAttribute namespace="##other" processContents="lax"/>
+ </xsd:complexType>
+
+ <xsd:element name="import" type="tImport"/>
+ <xsd:complexType name="tImport">
+ <xsd:attribute name="namespace" type="xsd:anyURI" use="required"/>
+ <xsd:attribute name="location" type="xsd:string" use="required"/>
+ <xsd:attribute name="importType" type="xsd:anyURI" use="required"/>
+ </xsd:complexType>
+
+</xsd:schema> \ No newline at end of file
diff --git a/xml/tests/testData/smartEnter/IDEADEV_29628_after.xml b/xml/tests/testData/smartEnter/IDEADEV_29628_after.xml
index 7df43358b5e4..faca654fd84f 100644
--- a/xml/tests/testData/smartEnter/IDEADEV_29628_after.xml
+++ b/xml/tests/testData/smartEnter/IDEADEV_29628_after.xml
@@ -1 +1 @@
-<label for="email"></label> \ No newline at end of file
+<label for="email"/> \ No newline at end of file
diff --git a/xml/tests/testData/smartEnter/idea103417_1.xml b/xml/tests/testData/smartEnter/idea103417_1.xml
new file mode 100644
index 000000000000..7f1a3e00852c
--- /dev/null
+++ b/xml/tests/testData/smartEnter/idea103417_1.xml
@@ -0,0 +1 @@
+<Button text="Say Hello"<caret> \ No newline at end of file
diff --git a/xml/tests/testData/smartEnter/idea103417_1_after.xml b/xml/tests/testData/smartEnter/idea103417_1_after.xml
new file mode 100644
index 000000000000..b217a6f2cd42
--- /dev/null
+++ b/xml/tests/testData/smartEnter/idea103417_1_after.xml
@@ -0,0 +1 @@
+<Button text="Say Hello"/> \ No newline at end of file
diff --git a/xml/tests/testData/smartEnter/idea103417_2.xml b/xml/tests/testData/smartEnter/idea103417_2.xml
new file mode 100644
index 000000000000..f520d7bf2554
--- /dev/null
+++ b/xml/tests/testData/smartEnter/idea103417_2.xml
@@ -0,0 +1 @@
+<Button text="Say Hello<caret>" \ No newline at end of file
diff --git a/xml/tests/testData/smartEnter/idea103417_2_after.xml b/xml/tests/testData/smartEnter/idea103417_2_after.xml
new file mode 100644
index 000000000000..b217a6f2cd42
--- /dev/null
+++ b/xml/tests/testData/smartEnter/idea103417_2_after.xml
@@ -0,0 +1 @@
+<Button text="Say Hello"/> \ No newline at end of file
diff --git a/xml/tests/testData/xml/DuplicateIdAttribute.xml b/xml/tests/testData/xml/DuplicateIdAttribute.xml
index 32eec98a5242..9fc688dc9115 100644
--- a/xml/tests/testData/xml/DuplicateIdAttribute.xml
+++ b/xml/tests/testData/xml/DuplicateIdAttribute.xml
@@ -4,7 +4,7 @@
<!ATTLIST b
id ID #REQUIRED>
]><a>
- <b id=<error>"1"</error>/>
- <b id=<error>"1"</error>/>
+ <b id="<error descr="Duplicate id reference">1</error>"/>
+ <b id="<error descr="Duplicate id reference">1</error>"/>
<b id="2"/>
</a> \ No newline at end of file
diff --git a/xml/tests/testData/xml/SchemaReferencesValidation.xsd b/xml/tests/testData/xml/SchemaReferencesValidation.xsd
index dabe7c315ea3..84b8b426a00e 100644
--- a/xml/tests/testData/xml/SchemaReferencesValidation.xsd
+++ b/xml/tests/testData/xml/SchemaReferencesValidation.xsd
@@ -7,24 +7,24 @@
>
<element name="Indication">
<complexType>
- <group ref="api:<error>MyGroup</error>"/>
+ <group ref="api:<error descr="Cannot resolve symbol 'api:MyGroup'">MyGroup</error>"/>
<group ref="api:aaa"/>
<attribute ref="xml:lang"/>
<attribute ref="xml:base"/>
<attribute ref="xml:space"/>
- <attribute ref="xml:<error>lang1</error>"/>
+ <attribute ref="xml:<error descr="Cannot resolve symbol 'xml:lang1'">lang1</error>"/>
</complexType>
</element>
<group name="aaa"></group>
<simpleType name="string" id="string">
<restriction base="anySimpleType">
- <whiteSpace value="preserve" id=<error>"string.preserve"</error>/>
+ <whiteSpace value="preserve" id="<error descr="Duplicate id reference">string.preserve</error>"/>
</restriction>
</simpleType>
<simpleType name="string" id="string2">
<restriction base="xs:anySimpleType">
- <whiteSpace value="preserve" id=<error>"string.preserve"</error>/>
+ <whiteSpace value="preserve" id="<error descr="Duplicate id reference">string.preserve</error>"/>
</restriction>
</simpleType>
</schema>