Search in sources :

Example 1 with AlienFormFileException

use of com.intellij.uiDesigner.compiler.AlienFormFileException in project intellij-community by JetBrains.

the class Form2SourceCompiler method getProcessingItems.

@NotNull
public ProcessingItem[] getProcessingItems(final CompileContext context) {
    final Project project = context.getProject();
    if (GuiDesignerConfiguration.getInstance(project).INSTRUMENT_CLASSES) {
        return ProcessingItem.EMPTY_ARRAY;
    }
    final ArrayList<ProcessingItem> items = new ArrayList<>();
    DumbService.getInstance(project).runReadActionInSmartMode(() -> {
        final CompileScope scope = context.getCompileScope();
        final CompileScope projectScope = context.getProjectCompileScope();
        final VirtualFile[] formFiles = projectScope.getFiles(StdFileTypes.GUI_DESIGNER_FORM, true);
        final CompilerManager compilerManager = CompilerManager.getInstance(project);
        final BindingsCache bindingsCache = new BindingsCache(project);
        try {
            final HashMap<String, VirtualFile> class2form = new HashMap<>();
            for (final VirtualFile formFile : formFiles) {
                if (compilerManager.isExcludedFromCompilation(formFile)) {
                    continue;
                }
                final String classToBind;
                try {
                    classToBind = bindingsCache.getBoundClassName(formFile);
                } catch (AlienFormFileException e) {
                    // ignore non-IDEA forms
                    continue;
                } catch (Exception e) {
                    addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.process.form.file", e)), formFile);
                    continue;
                }
                if (classToBind == null) {
                    continue;
                }
                final VirtualFile sourceFile = findSourceFile(context, formFile, classToBind);
                if (sourceFile == null) {
                    if (scope.belongs(formFile.getUrl())) {
                        addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.class.to.bind.does.not.exist", classToBind)), formFile);
                    }
                    continue;
                }
                final boolean inScope = scope.belongs(sourceFile.getUrl()) || scope.belongs(formFile.getUrl());
                final VirtualFile alreadyProcessedForm = class2form.get(classToBind);
                if (alreadyProcessedForm != null) {
                    if (inScope) {
                        addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.duplicate.bind", classToBind, alreadyProcessedForm.getPresentableUrl())), formFile);
                    }
                    continue;
                }
                class2form.put(classToBind, formFile);
                if (!inScope) {
                    continue;
                }
                items.add(new MyInstrumentationItem(sourceFile, formFile));
            }
        } finally {
            bindingsCache.close();
        }
    });
    return items.toArray(new ProcessingItem[items.size()]);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) IOException(java.io.IOException) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) Project(com.intellij.openapi.project.Project) FormErrorInfo(com.intellij.uiDesigner.compiler.FormErrorInfo) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with AlienFormFileException

use of com.intellij.uiDesigner.compiler.AlienFormFileException in project intellij-community by JetBrains.

the class Generator method exposeForm.

/**
   * @param rootContainer output parameter; should be LwRootContainer[1]
   */
public static FormProperty[] exposeForm(final Project project, final VirtualFile formFile, final LwRootContainer[] rootContainer) throws MyException {
    final Module module = ModuleUtil.findModuleForFile(formFile, project);
    LOG.assertTrue(module != null);
    final PsiPropertiesProvider propertiesProvider = new PsiPropertiesProvider(module);
    final Document doc = FileDocumentManager.getInstance().getDocument(formFile);
    final LwRootContainer _rootContainer;
    try {
        _rootContainer = Utils.getRootContainer(doc.getText(), propertiesProvider);
    } catch (AlienFormFileException e) {
        throw new MyException(e.getMessage());
    } catch (Exception e) {
        throw new MyException(UIDesignerBundle.message("error.cannot.process.form.file", e));
    }
    rootContainer[0] = _rootContainer;
    final String classToBind = _rootContainer.getClassToBind();
    if (classToBind == null) {
        throw new MyException(UIDesignerBundle.message("error.form.is.not.bound.to.a.class"));
    }
    final PsiClass boundClass = FormEditingUtil.findClassToBind(module, classToBind);
    if (boundClass == null) {
        throw new MyException(UIDesignerBundle.message("error.bound.class.does.not.exist", classToBind));
    }
    final ArrayList<FormProperty> result = new ArrayList<>();
    final MyException[] exception = new MyException[1];
    FormEditingUtil.iterate(_rootContainer, new FormEditingUtil.ComponentVisitor<LwComponent>() {

        public boolean visit(final LwComponent component) {
            final String binding = component.getBinding();
            if (binding == null) {
                return true;
            }
            final PsiField[] fields = boundClass.getFields();
            PsiField field = null;
            for (int i = fields.length - 1; i >= 0; i--) {
                if (binding.equals(fields[i].getName())) {
                    field = fields[i];
                    break;
                }
            }
            if (field == null) {
                exception[0] = new MyException(UIDesignerBundle.message("error.field.not.found.in.class", binding, classToBind));
                return false;
            }
            final PsiClass fieldClass = getClassByType(field.getType());
            if (fieldClass == null) {
                exception[0] = new MyException(UIDesignerBundle.message("error.invalid.binding.field.type", binding, classToBind));
                return false;
            }
            if (instanceOf(fieldClass, JTextComponent.class.getName())) {
                result.add(new FormProperty(component, "getText", "setText", String.class.getName()));
            } else if (instanceOf(fieldClass, JCheckBox.class.getName())) {
                result.add(new FormProperty(component, "isSelected", "setSelected", boolean.class.getName()));
            }
            return true;
        }
    });
    if (exception[0] != null) {
        throw exception[0];
    }
    return result.toArray(new FormProperty[result.size()]);
}
Also used : ArrayList(java.util.ArrayList) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) LwRootContainer(com.intellij.uiDesigner.lw.LwRootContainer) Document(com.intellij.openapi.editor.Document) IncorrectOperationException(com.intellij.util.IncorrectOperationException) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) LwComponent(com.intellij.uiDesigner.lw.LwComponent) Module(com.intellij.openapi.module.Module) PsiPropertiesProvider(com.intellij.uiDesigner.PsiPropertiesProvider) FormEditingUtil(com.intellij.uiDesigner.FormEditingUtil)

Example 3 with AlienFormFileException

use of com.intellij.uiDesigner.compiler.AlienFormFileException in project intellij-community by JetBrains.

the class GenerateMainAction method actionPerformed.

public void actionPerformed(AnActionEvent e) {
    final Project project = e.getData(CommonDataKeys.PROJECT);
    assert project != null;
    final Editor editor = e.getData(CommonDataKeys.EDITOR);
    assert editor != null;
    final int offset = editor.getCaretModel().getOffset();
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    PsiClass psiClass = PsiTreeUtil.getParentOfType(file.findElementAt(offset), PsiClass.class);
    assert psiClass != null;
    if (!PsiUtil.hasDefaultConstructor(psiClass)) {
        Messages.showMessageDialog(project, UIDesignerBundle.message("generate.main.no.default.constructor"), UIDesignerBundle.message("generate.main.title"), Messages.getErrorIcon());
        return;
    }
    final List<PsiFile> boundForms = FormClassIndex.findFormsBoundToClass(project, psiClass.getQualifiedName());
    final LwRootContainer rootContainer;
    try {
        rootContainer = Utils.getRootContainer(boundForms.get(0).getText(), null);
    } catch (AlienFormFileException ex) {
        Messages.showMessageDialog(project, "The form bound to the class is not a valid IntelliJ IDEA form", UIDesignerBundle.message("generate.main.title"), Messages.getErrorIcon());
        return;
    } catch (Exception ex) {
        LOG.error(ex);
        return;
    }
    if (rootContainer.getComponentCount() == 0) {
        Messages.showMessageDialog(project, UIDesignerBundle.message("generate.main.empty.form"), UIDesignerBundle.message("generate.main.title"), Messages.getErrorIcon());
        return;
    }
    String rootBinding = rootContainer.getComponent(0).getBinding();
    if (rootBinding == null || psiClass.findFieldByName(rootBinding, true) == null) {
        Messages.showMessageDialog(project, UIDesignerBundle.message("generate.main.no.root.binding"), UIDesignerBundle.message("generate.main.title"), Messages.getErrorIcon());
        return;
    }
    @NonNls final StringBuilder mainBuilder = new StringBuilder("public static void main(String[] args) { ");
    final JavaCodeStyleManager csm = JavaCodeStyleManager.getInstance(project);
    SuggestedNameInfo nameInfo = csm.suggestVariableName(VariableKind.LOCAL_VARIABLE, "frame", null, null);
    String varName = nameInfo.names[0];
    mainBuilder.append(JFrame.class.getName()).append(" ").append(varName).append("= new ").append(JFrame.class.getName());
    mainBuilder.append("(\"").append(psiClass.getName()).append("\");");
    mainBuilder.append(varName).append(".setContentPane(new ").append(psiClass.getQualifiedName()).append("().").append(rootBinding).append(");");
    mainBuilder.append(varName).append(".setDefaultCloseOperation(").append(JFrame.class.getName()).append(".EXIT_ON_CLOSE);");
    mainBuilder.append(varName).append(".pack();");
    mainBuilder.append(varName).append(".setVisible(true);");
    mainBuilder.append("}\n");
    CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            PsiMethod method = JavaPsiFacade.getInstance(file.getProject()).getElementFactory().createMethodFromText(mainBuilder.toString(), file);
            List<PsiGenerationInfo<PsiMethod>> infos = Collections.singletonList(new PsiGenerationInfo<>(method));
            List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersAtOffset(file, offset, infos);
            resultMembers.get(0).positionCaret(editor, false);
        } catch (IncorrectOperationException e1) {
            LOG.error(e1);
        }
    }), null, null);
}
Also used : NonNls(org.jetbrains.annotations.NonNls) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) LwRootContainer(com.intellij.uiDesigner.lw.LwRootContainer) IncorrectOperationException(com.intellij.util.IncorrectOperationException) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) List(java.util.List) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) PsiGenerationInfo(com.intellij.codeInsight.generation.PsiGenerationInfo)

Example 4 with AlienFormFileException

use of com.intellij.uiDesigner.compiler.AlienFormFileException in project intellij-community by JetBrains.

the class FormWordsScanner method processWords.

@Override
public void processWords(CharSequence fileText, final Processor<WordOccurrence> processor) {
    super.processWords(fileText, processor);
    try {
        LwRootContainer container = Utils.getRootContainer(fileText.toString(), null);
        String className = container.getClassToBind();
        if (className != null) {
            processClassAndPackagesNames(className, processor);
        }
        FormEditingUtil.iterate(container, new FormEditingUtil.ComponentVisitor() {

            WordOccurrence occurence;

            public boolean visit(IComponent iComponent) {
                String componentClassName = iComponent.getComponentClassName();
                processClassAndPackagesNames(componentClassName, processor);
                final String binding = iComponent.getBinding();
                if (binding != null) {
                    if (occurence == null)
                        occurence = new WordOccurrence(binding, 0, binding.length(), WordOccurrence.Kind.FOREIGN_LANGUAGE);
                    else
                        occurence.init(binding, 0, binding.length(), WordOccurrence.Kind.FOREIGN_LANGUAGE);
                    processor.process(occurence);
                }
                return true;
            }
        });
    } catch (AlienFormFileException | JDOMParseException | UnexpectedFormElementException ex) {
    // ignore
    } catch (Exception e) {
        LOG.error("Error indexing form file", e);
    }
}
Also used : JDOMParseException(org.jdom.input.JDOMParseException) WordOccurrence(com.intellij.lang.cacheBuilder.WordOccurrence) IComponent(com.intellij.uiDesigner.lw.IComponent) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) LwRootContainer(com.intellij.uiDesigner.lw.LwRootContainer) FormEditingUtil(com.intellij.uiDesigner.FormEditingUtil) UnexpectedFormElementException(com.intellij.uiDesigner.compiler.UnexpectedFormElementException) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) JDOMParseException(org.jdom.input.JDOMParseException) UnexpectedFormElementException(com.intellij.uiDesigner.compiler.UnexpectedFormElementException)

Example 5 with AlienFormFileException

use of com.intellij.uiDesigner.compiler.AlienFormFileException in project intellij-community by JetBrains.

the class LwRootContainer method read.

public void read(final Element element, final PropertiesProvider provider) throws Exception {
    if (element == null) {
        throw new IllegalArgumentException("element cannot be null");
    }
    if (!Utils.FORM_NAMESPACE.equals(element.getNamespace().getURI())) {
        throw new AlienFormFileException();
    }
    if (!"form".equals(element.getName())) {
        throw new UnexpectedFormElementException("unexpected element: " + element);
    }
    setId("root");
    myClassToBind = element.getAttributeValue(UIFormXmlConstants.ATTRIBUTE_BIND_TO_CLASS);
    // Constraints and properties
    for (Iterator i = element.getChildren().iterator(); i.hasNext(); ) {
        final Element child = (Element) i.next();
        if (child.getName().equals(UIFormXmlConstants.ELEMENT_BUTTON_GROUPS)) {
            readButtonGroups(child);
        } else if (child.getName().equals(UIFormXmlConstants.ELEMENT_INSPECTION_SUPPRESSIONS)) {
            readInspectionSuppressions(child);
        } else {
            final LwComponent component = createComponentFromTag(child);
            addComponent(component);
            component.read(child, provider);
        }
    }
    myMainComponentBinding = element.getAttributeValue("stored-main-component-binding");
}
Also used : Element(org.jdom.Element) Iterator(java.util.Iterator) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) UnexpectedFormElementException(com.intellij.uiDesigner.compiler.UnexpectedFormElementException)

Aggregations

AlienFormFileException (com.intellij.uiDesigner.compiler.AlienFormFileException)5 LwRootContainer (com.intellij.uiDesigner.lw.LwRootContainer)3 Project (com.intellij.openapi.project.Project)2 FormEditingUtil (com.intellij.uiDesigner.FormEditingUtil)2 UnexpectedFormElementException (com.intellij.uiDesigner.compiler.UnexpectedFormElementException)2 IncorrectOperationException (com.intellij.util.IncorrectOperationException)2 ArrayList (java.util.ArrayList)2 PsiGenerationInfo (com.intellij.codeInsight.generation.PsiGenerationInfo)1 WordOccurrence (com.intellij.lang.cacheBuilder.WordOccurrence)1 Document (com.intellij.openapi.editor.Document)1 Editor (com.intellij.openapi.editor.Editor)1 Module (com.intellij.openapi.module.Module)1 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)1 SuggestedNameInfo (com.intellij.psi.codeStyle.SuggestedNameInfo)1 PsiPropertiesProvider (com.intellij.uiDesigner.PsiPropertiesProvider)1 FormErrorInfo (com.intellij.uiDesigner.compiler.FormErrorInfo)1 IComponent (com.intellij.uiDesigner.lw.IComponent)1 LwComponent (com.intellij.uiDesigner.lw.LwComponent)1 IOException (java.io.IOException)1